我知道以下代码将创建一个字符数组并保留在内存中直到程序结束:
char* str = "this is a string";
对于这个语句,创建一个本地字符数组,当 str 超出范围时将被释放:
char str[] = "this is a string";
我很好奇的是,当我这样写时会发生什么:
std::string str = "this is a string";
str 应该在它自己的内存(本地)中复制字符串,但是字符串文字本身呢?它会拥有程序的生命周期还是会在 str 超出范围时被释放?
最佳答案
当你写这个的时候
std::string str = "this is a string";
C++ 应该找到 std::string
的构造函数,它接受 const char*
,调用它来创建一个临时对象,调用复制构造函数将该临时对象复制到str
,然后销毁临时对象。
但是,有一个优化允许C++编译器跳过临时对象的构造和销毁,所以结果是一样的
std::string str("this is a string");
but what about the string literal itself? Will it have the lifetime of the program or will it be freed when str goes out of scope?
您的程序无法访问以这种方式使用的字符串文字本身。通常,C++ 将它放在与其他字符串文字相同的段中,使用它传递给 std::string
的构造函数,然后忘记它。允许优化器消除所有字符串文字中的重复项,包括仅用于初始化其他对象的文字。
关于c++ - 将字符串文字分配给 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32413700/