char* 和std::string的生命周期

std::string跟普通的c++对象一样,在对应的local/global的域内自动释放(包括string指向的字符串)。

因此

{

std::string abc = "abc";

}

"abc"在花括号外就被自动释放了。

而char* 不一样,如果不用New,而是用char* abc = "abc";

abc将成为string literal,是一个static object,将在进程退出后释放。

 


Yes, the lifetime of a local variable is within the scope({,}) in which it is created.

Local variables have automatic or local storage. Automatic because they are automatically destroyed once the scope within which they are created ends.

However, What you have here is a string literal, which is allocated in an implementation-defined read-only memory. String literals are different from local variables and they remain alive throughout the program lifetime. They have static duration  lifetime.

 

 

 
posted @ 2023-02-16 10:26  xuyv  阅读(168)  评论(0编辑  收藏  举报