#include <iostream>
#include <string>

using namespace std;

class Foo
{
public:
    Foo();
    ~Foo();
    Foo(const Foo& other);
    Foo& operator = (const Foo& other);
public:
    string GetString() const;

    Foo Copy();
private:
    int number_;
};

Foo::Foo()
{
    number_ = 0;
}

Foo::~Foo()
{
    number_ = 100;
}

Foo::Foo(const Foo& other)
{
    number_ = other.number_;
}

Foo& Foo::operator = (const Foo& other)
{
    if (this == &other)
        return *this;
    number_ = other.number_;
    return *this;
}

string Foo::GetString() const
{
    return to_string(number_);
}

Foo Foo::Copy()
{
    return *this;
}

int main()
{
    Foo foo;
    const char* p = foo.GetString().c_str();//1
    p = foo.Copy().GetString().c_str();//2
    return 0;
}

调试到标记的1,2行,出现
C++中临时变量的生存期C++中临时变量的生存期这也就意味着当前行执行结束后,临时变量就gg了。写代码时需要注意。

相关文章: