VC的另一个BUG++ 2010年?关于在标头中声明常量 REFERENCE
几行代码胜千字:
我有三个简单的文件: header.h、main.cpp、other.cpp
// header.h
#pragma once
inline const int& GetConst()
{
static int n = 0;
return n;
}
const int& r = GetConst();
// main.cpp
#include "header.h"
int main()
{
return 0;
}
// other.cpp
#include "header.h"
在编译最简单的项目时,VC++ 2010 抱怨如下:
ClCompile:
other.cpp
main.cpp
Generating Code...
other.obj : error LNK2005: "int const & const r" (?r@@3ABHB) already defined in main.obj
D:\Test\Debug\bug.exe : fatal error LNK1169: one or more multiply defined symbols found
Build FAILED.
Time Elapsed 00:00:00.29
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
我确信这是 VC++ 2010 的错误,因为以下两个参考:
1、C++ 标准说:(n3126 第 140 页)
“声明为 const 且未显式声明为 extern 的对象具有内部链接。”
2、MSDN 说:(位于:http://msdn .microsoft.com/en-us/library/357syhfh(VS.80).aspx)
“在 C 中,常量值默认为外部链接,因此它们只能出现在源文件中。在 C++ 中,常量值默认为到内部链接,这允许它们出现在头文件中。
const 关键字也可以在指针声明中使用。”
Several lines of code are worth a thousand words:
I have three simple files: header.h, main.cpp, other.cpp
// header.h
#pragma once
inline const int& GetConst()
{
static int n = 0;
return n;
}
const int& r = GetConst();
// main.cpp
#include "header.h"
int main()
{
return 0;
}
// other.cpp
#include "header.h"
When compiling the simplest project, the VC++ 2010 complains as follows:
ClCompile:
other.cpp
main.cpp
Generating Code...
other.obj : error LNK2005: "int const & const r" (?r@@3ABHB) already defined in main.obj
D:\Test\Debug\bug.exe : fatal error LNK1169: one or more multiply defined symbols found
Build FAILED.
Time Elapsed 00:00:00.29
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I am sure this is a bug of VC++ 2010, because of the following two references:
1, The C++ standard says: (at page 140 of n3126)
"Objects declared const and not explicitly declared extern have internal linkage."
2, The MSDN says: (at: http://msdn.microsoft.com/en-us/library/357syhfh(VS.80).aspx)
"In C, constant values default to external linkage, so they can appear only in source files. In C++, constant values default to internal linkage, which allows them to appear in header files.
The const keyword can also be used in pointer declarations."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您引用的 C++ 标准段落如下(C++03 7.1.1/6):
您尚未声明对象。您已声明引用。引用不是对象。也就是说,3.5/3 说:
但是,8.3.2/1 说:
因此,虽然 const 限定的引用具有内部链接,但不可能对引用进行 const 限定。
示例程序中的引用不是 const 限定的,它是对 const 限定的
int
的引用。The paragraph you cite from the C++ Standard reads (C++03 7.1.1/6):
You have not declared an object. You have declared a reference. A reference is not an object. That said, 3.5/3 says:
However, 8.3.2/1 says:
So, while a const-qualified reference would have internal linkage, it's not possible to const-qualify a reference.
The reference in your sample program is not const-qualified, it's a reference to a const-qualified
int
.