gpt4 book ai didi

c++ - const 引用在 C++ 中是否有外部链接?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:18 25 4
gpt4 key购买 nike

根据 C++ 1998 标准第 3.5 节的第 3 条,const 引用具有内部链接。

A name having namespace scope (3.3.5) has internal linkage if it is the name of

  • an object, reference, function or function template that is explicitly declared static or,

  • an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage; or

  • a data member of an anonymous union.

但是为什么编译下面的代码会产生多重定义冲突呢?

// a.cpp
const int& a = 1;

int main()
{
return 0;
}

// b.cpp
const int& a = 1;

然后编译代码。

$ g++ a.cpp b.cpp
/tmp/ccb5Qi0M.o:(.bss+0x0): multiple definition of `a'
/tmp/ccD9vrzP.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

如果把const引用改成const,如下

// a.cpp
const int a = 1;

int main()
{
return 0;
}

// b.cpp
const int a = 1;

编译就OK了。

最佳答案

引用本身不是const,只是它引用的对象;所以(可以说)这条规则没有给出引用内部链接。

将引用声明为 const 是没有意义的。 C++11标准明确了措辞:

a variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage

没有提及声明为 const 的引用的荒谬概念。

关于c++ - const 引用在 C++ 中是否有外部链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22765649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com