35

我正在做一个小项目,并遇到了以下情况:

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

我的问题是如果GetValue() 返回 NULLmyString变成一个空字符串?它是未定义的吗?还是会出现段错误?

4

3 回答 3

62

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

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

要求: s 不得为空指针。

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

于 2012-05-27T05:48:21.823 回答
13

这是运行时错误。

你应该做这个:

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.

于 2012-05-27T05:46:35.920 回答
7

我的问题是如果 GetValue() 返回 NULL myString 变成一个空字符串?它是未定义的吗?还是会出现段错误?

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

于 2012-05-27T05:51:06.393 回答