我想知道我是否误解了某些内容:复制构造函数是否std::string 不复制其内容?
string str1 = "Hello World";
string str2(str1);
if(str1.c_str() == str2.c_str()) // Same pointers!
printf ("You will get into the IPC hell very soon!!");
Run Code Online (Sandbox Code Playgroud)
这将打印出"你很快就会进入IPC地狱!" 它让我烦恼
这是正常的行为std::string吗?我在某处读到它通常会做一个深层复制.
但是,这可以按预期工作:
string str3(str1.c_str());
if(str1.c_str() == str3.c_str()) // Different pointers!
printf ("You will get into the IPC hell very soon!!");
else
printf ("You are safe! This time!");
Run Code Online (Sandbox Code Playgroud)
它将内容复制到新字符串中.
我想在布尔上下文中评估某个类的实例.或者更清楚一点,我想定义对象如果直接在布尔上下文中使用它会如何反应.
这是一个例子:
class Foo
{
int state;
Foo(): state(1) {}
bool checkState()
{
return (state >= 0);
}
void doWork()
{
/*blah with state*/
}
};
int main()
{
Foo obj;
//while(obj.checkState()) //this works perfectly, and thats what i indent to do!
while(obj) //this is what want to write
obj.doWork();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
好吧,它只是一个很好的:-),但这有可能吗?如果有,怎么样?
谢谢!