加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C堆栈分配的对象分配和析构函数调用

发布时间:2020-12-16 10:06:23 所属栏目:百科 来源:网络整理
导读:我正在尝试理解在为堆栈上分配的对象分配新值时看起来有些奇怪的行为(对于相同的数据集,析构函数被调用两次).我将从代码片段及其输出开始: class Foo { public: Foo(const string name) : m_name(name) { log("constructor"); } ~Foo() { log("destructor")
我正在尝试理解在为堆栈上分配的对象分配新值时看起来有些奇怪的行为(对于相同的数据集,析构函数被调用两次).我将从代码片段及其输出开始:

class Foo {
    public:
        Foo(const string& name) : m_name(name) {
            log("constructor");
        }
        ~Foo() {
            log("destructor");
        }
        void hello() {
            log("hello");
        }
    private:
        string m_name;
        void log(const string& msg) {
            cout << "Foo." << this << " [" << m_name << "] " << msg << endl;
        }
    };

    int main() {

        {
            Foo f {"f1"};
            f.hello();

            f = Foo {"f2"};
            f.hello();
        }
        cout << "scope end" << endl;
    }

输出:

Foo.0x7fff58c66a58 [f1] constructor
    Foo.0x7fff58c66a58 [f1] hello
    Foo.0x7fff58c66a18 [f2] constructor
    Foo.0x7fff58c66a18 [f2] destructor
    Foo.0x7fff58c66a58 [f2] hello
    Foo.0x7fff58c66a58 [f2] destructor
    scope end

我期望发生的事情:

> 0x … 58在堆栈上创建/初始化
> 0x … 18在堆栈上创建/初始化
> Foo析构函数调用0x … 58(带有f1数据)
> Foo析构函数调用0x … 18(带有f2数据)

实际发生了什么:

> 0x … 58在堆栈上创建/初始化
> 0x … 18在堆栈上创建/初始化
>来自0x … 18(f2)的数据被复制到0x … 58
> Foo析构函数调用0x … 18(带有f2数据)
> Foo析构函数调用0x … 58(也使用f2数据)

所以最后,对于相同的数据(f2),Foo析构函数被调用两次.很明显我错过了一些关于内部如何运作的内容,那么请有人指出我正确的方向吗?

解决方法

你的实例f被分配了一个Foo {“f2”}的副本,它不是一个新的结构.

添加以下operator = override来说明实际发生的情况.

Foo& Foo::operator=(const Foo& other) {
    cout << "Foo::operator=(const Foo& other)" << endl;
    m_name = other.m_name;  
    return *this;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读