我知道下面的代码会创建一个字符数组并一直存在内存中直到程序结束:
char* str = "this is a string";
关于这个声明,它创建了一个字符的本地数组,并将在str超出作用域时被释放:
char str[] = "this is a string";
我感到好奇的是,如果我这样写会发生什么:
std::string str = "this is a string";
str应该将字符串复制到它自己的内存(本地),但是字符串本身会怎样?它的生命周期是整个程序还是在str超出作用域时被释放?
static
存储期,因此它将始终存在于程序的整个生命周期中。 - The Paramagnetic Croissantstd::basic_string
不拥有字面值,因此它的生命周期不由str
确定。 - edmz