我正在开发一个项目,当我为一个类创建构造函数时,我将一些变量设置为默认值。我将 std::string
设置为 NULL
,结果出现错误。但是,当我在同一行定义 std::string
并将其设置为 NULL
时,它可以正常工作,不会出现任何错误。我想知道为什么
第一个示例
std::string text = NULL;
工作了,并且
第二个示例
std::string text;
text = NULL;
没用。现在我知道你不应该将字符串设置为 NULL 或 0,但我偶然发现了这一点。
第一个示例是否调用一个采用 char*
的构造函数,并认为 0 是指向 char 的指针?我认为 =
也调用了构造函数,所以我不明白为什么它们不能同时工作,除非 std::string
专门重载 =
运算符。
我正在使用 Microsoft Visual Studio Express 2013
最佳答案
NULL
的值计算结果为0
。
现在,std::string text = NULL;
将调用采用const char*
的构造函数并尝试复制数据,但从NULL
开始没有指向任何内容,运行时会发生错误,我得到(使用 gcc 5.2):
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
因为,没有为 std::string
和 int
(或 size_t
)定义 operator=
, text = NULL;
将无法编译。
关于c++ - 在定义期间将 std::string 设置为 0 与将 std::string 设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33706112/