Why Doesn't the Visual Studio 2010 Debugger See static const Class Members?

假如想象 提交于 2019-12-05 03:21:28
Ben Voigt

Visual C++ erroneously provides a weak definition (evidence provided in this answer) based on the declaration inside the class, despite clear language in the Standard:

The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator.

According to the another rule in the Standard, no definition is needed if the member isn't odr-used.

Whether there's an explicit definition or weak definition erroneously provided by Visual C++ makes no difference however. If the member isn't odr-used, the linker will not see any references to it and will remove it, leaving the debugger confused about whether it ever existed. With the Microsoft linker, you can inhibit this optimization using /OPT:NOREF.

Ultimately that's not something you want to do in production code, though, since you'll have all kinds of vestigial stuff from the standard library left over in your application. But for temporary use during debugging that's a reasonable setting.

You could add a definition for your static data member at global namespace scope:

const int Foo::A;

Adding the static data member definition, which is not necessary but allowed, seems to solve your problem.

I tested this on a debug build with VS2010, and the value of A is correctly displayed in the debug window when the definition is present (while an error message is reported when the definition is missing, consistently with what you mention).

This isn't a bug. The compiler can (and almost always will) optimize out static constant basic types. Instead of allocating storage for A, the compiler is just inlining the value of A into the compiled instructions.

Because A isn't stored anywhere, it has no address, so the debugger cannot view it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!