问题描述
我正在移植现有的代码编译gcc 4.7.2,并遇到一个奇怪的问题与nullptr。我已经成功地把它归结为一个简单的测试用例:
I am porting existing code to compile under gcc 4.7.2 and have run into a strange issue with nullptr. I have managed to boil it down to a simple test case:
#include <stdio.h>
const char* g_marker = "Original value";
void SetMarker( const char* s )
{
g_marker = s;
}
char* Test1()
{
return SetMarker( "I was here 1" ), nullptr;
}
char* Test2()
{
SetMarker( "I was here 2" );
return nullptr;
}
char* Test3()
{
return SetMarker( "I was here 3"), (char*)NULL;
}
int main()
{
char* returnValue = Test1();
printf( "%s\n", g_marker );
}
使用g ++ test.cpp -o test -std = c ++ 0x。
Compile this with g++ test.cpp -o test -std=c++0x.
我期望的输出是我在这里1,但我得到原始值,表示SetMarker从未被调用。
The output I would expect is "I was here 1", but I get "Original value", indicating that SetMarker is never called.
调用Test2或Test3给出预期输出。
Calling either Test2 or Test3 gives the expected output.
我使用的代码使用Test3中看到的模式没有转换在前面的NULL - 这给无效转换从int到char *的错误,所以我开始将所有这些NULL更改为nullptr。不幸的是,这只是不正确的行为。
The code I'm working with uses the pattern seen in Test3 - originally without the cast in front of the NULL - that gave an error on invalid conversion from int to char* so I started changing all those NULLs to nullptr. Unfortunately, that just doesn't behave correctly.
我可能被迫改变代码使用Test2中的模式(我喜欢反正),但我好奇地知道这是否是编译器中的错误,或者如果我缺少某些东西。
I'm likely forced to change the code to use the pattern in Test2 (which I prefer anyway) but I'm curious to know if this is a bug in the compiler, or if I'm missing something.
推荐答案
g ++: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52988
g ++在类型 nullptr_t
的表达式中放弃副作用,假设所有 nullptr_t
值是等价的(它们是,但这并不意味着你可以忽略副作用)
g++ was discarding side-effects in expressions of type nullptr_t
, on the assumption that all nullptr_t
values are equivalent (which they are, but that doesn't mean that you can ignore side effects!)
在4.8.0版本中; 4.x分支上的新发行版(4.6.4和4.7.3)也应该有修复。
This is fixed in the 4.8.0 release; new releases on the 4.x branches (4.6.4 and 4.7.3) should also have the fix.
这篇关于gcc nullptr问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!