Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

c++ - gcc nullptr issue

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
", g_marker );
}

Compile this with g++ test.cpp -o test -std=c++0x.

The output I would expect is "I was here 1", but I get "Original value", indicating that SetMarker is never called.

Calling either Test2 or Test3 gives the expected output.

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a bug in g++: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52988

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!)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...