在定义期间将std :: string设置为0,而将std :: string设置为0 [英] Setting std::string to 0 during definition vs setting std::string to 0
问题描述
我正在处理一个我的项目,当我正在为一个类的构造函数,我将一些我的变量设置为默认值。我去设置 std :: string
到 NULL
,它给了一个错误。但是当我在同一行上定义一个 std :: string
并将其设置为 NULL
。我想知道为什么
第一个例子
std :: string text = NULL;
工作,
第二个示例
std :: string text;
text = NULL;
无法使用。现在我知道你不应该将字符串设置为NULL或0,但我发现这是意外。
第一个例子调用一个构造函数, c $ c> char * ,认为0是指向char的指针?我认为 =
也调用了一个构造函数,所以我不知道为什么他们不会工作,除非 std :: string
具体重载 =
运算符。
我使用Microsoft Visual Studio Express 2013
NULL
计算为 0
。
现在, std :: string text = NULL;
将调用构造函数 const char *
并尝试复制数据,但由于 NULL
没有指向任何东西,运行时会出现错误,我得到了(与gcc 5.2):
在抛出'std :: logic_error'实例后调用终止
what():basic_string :: _ M_construct null无效
$ c $由于 std中没有定义 operator =
,因此
$ b < :string
和 int
(或 size_t
), text = NULL;
将无法编译。
I was working on one my projects, and while I was making the constructor for a class, I was setting some of my variables to a default value. I went to set an std::string
to NULL
, and it gave me an error. But when I define an std::string
and set it to NULL
on the same line, it works without any errors. I was wondering why
First Example
std::string text = NULL;
worked, and
Second Example
std::string text;
text = NULL;
didn't work. Now I know you shouldn't set a string to NULL, or 0, but I found this on accident.
Does the first example call a constructor that takes a char*
, and thinking that 0 is a pointer to a char? I thought =
called a constructor too, so I don't get why they wouldn't both work, unless std::string
specifically overloads the =
operator.
I am using Microsoft Visual Studio Express 2013
解决方案 Value of NULL
evaluates to 0
.
Now, std::string text = NULL;
will call constructor taking const char*
and try to copy the data, but since NULL
doesn't point to anything, an error will occur at run-time, I am getting (with gcc 5.2) :
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
Since, there is no operator=
defined for std::string
and int
(or size_t
), text = NULL;
will not compile.
这篇关于在定义期间将std :: string设置为0,而将std :: string设置为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!