字符串是否动态分配?

Dal*_*eme 3 c++ string

我有一个简单的问题.我有以下代码:

class Class1
{
    Class1();
    ~Class1();
    void func1();
private:
    char* c;

}

void Class1::func1()
{
    string s = "something";
    this->c = s.c_str();
}
Run Code Online (Sandbox Code Playgroud)

c存储"something"的时候func1()完成?

小智 8

不会.它会调用未定义的行为. (如果你取消引用指针,无论如何.)由于s是一个具有自动存储持续时间的块范围对象,它在函数返回时被销毁,并且使得返回的指针.c_str()无效.


为什么不使用std::string成员变量呢?