2012-05-27 48 views
20

我工作的一个小项目,来到一个情况下面发生了:将nullptr分配给std :: string是安全的吗?

std::string myString; 
#GetValue() returns a char* 
myString = myObject.GetValue(); 

我的问题是,如果GetValue()返回NULL myString成为一个空字符串?它是不确定的吗?或它会segfault?

+1

这个问题是非常相似的:http://stackoverflow.com/questions/2407711/avoiding-improper-stdstring-initialization-with-null-const-char-using-g – chris

+2

微软总是有一个错误,分配一个0x0以std :: string确定。通过查看你的代码,它看起来像你是一个微软的人,所以它可能适合你。但是..否则它会触发一个SIGSEGV。 – 2012-05-27 05:55:57

回答

38

有趣的小问题。根据C++ 11标准, 21.4.2.9,

basic_string(const charT* s, const Allocator& a = Allocator()); 

要求:s不得为空指针。

由于该标准并未要求库在不满足此特定要求时抛出异常,因此传递空指针似乎会引发未定义的行为。

9

这是运行时错误。

你应该这样做:

myString = ValueOrEmpty(myObject.GetValue()); 

其中ValueOrEmpty被定义为:

std::string ValueOrEmpty(const char* s) 
{ 
    return s == nullptr ? std::string() : s; 
} 

或者你可以返回const char*(,更理智):

const char* ValueOrEmpty(const char* s) 
{ 
    return s == nullptr ? "" : s; 
} 

如果您返回const char*,然后在呼叫地点,它将转换为std::string

4

我的问题是如果GetValue()返回NULL myString变成一个空字符串?它是不确定的吗?或它会segfault?

这是未定义的行为。编译器和运行时可以做任何想要的事情,并且仍然符合规范。