3

考虑以下类:

struct MyClass {
    int mId;
    MyClass(int id): mId(id) {}
   ~MyClass() { std::cout << "deleting: " << mId << std::endl; }
};

以及用法:

std::shared_ptr<MyClass> p(new MyClass(0));
MyClass& m = *p;
m = MyClass(2);

结果是:

deleting: 2
deleting: 2

请帮助我理解:

  1. 为什么有两个MyClass(2)对象(在析构函数日志中做出的假设)
  2. 这是内存泄漏吗?不应该MyClass(0)泄漏吗?

谢谢你。

4

2 回答 2

4

没有内存泄漏。这段代码:

m = MyClass(2);

创建一个类型的临时对象,使用 的(默认生成的)复制赋值运算符MyClass复制到该临时对象,然后将其销毁。最终,超出范围,其析构函数破坏了is 指向的实例(绑定到的实例)。mMyClasspMyClassm

如果我们明确说明所有隐式调用,就会发生这种情况:

// std::shared_ptr<MyClass> p(new MyClass(0));
tmp1.MyClass(0);
p.shared_ptr(&tmp1);

// MyClass& m = *p;
p.operator* ();

// m = MyClass(2);
tmp2.MyClass(2);
m.operator= (tmp2);
tmp2.~MyClass();

// p goes out of scope
p.~shared_ptr();
tmp1.~MyClass();
于 2013-09-12T15:19:58.270 回答
2

这样做是为了更清楚地了解创造破坏:

struct MyClass {
    int mId;
    MyClass(int id): mId(id) {std::cout << "Creating: " << this << "(" << mId << ")\n";}
   ~MyClass()                {std::cout << "Deleting: " << this << "(" << mId << ")\n";}
    MyClass(MyClass const& c)
                             {std::cout << "Copy:     " << this << "(" << mId << ")\n"
                                           "    From: " << &c   << "(" << c.mId << ")\n";
                              mId=c.mId;
                             }
    MyClass& operator=(MyClass const& c)
                             {std::cout << "Assign:   " << this << "(" << mId << ")\n"
                                           "    From: " << &c   << "(" << c.mId << ")\n";
                              mId=c.mId;
                             }
};

当我跑步时,我得到:

Creating: 0x7fc741c000e0(0)
Creating: 0x7fff50ac38c0(2)
Assign:   0x7fc741c000e0(0)
    From: 0x7fff50ac38c0(2)
Deleting: 0x7fff50ac38c0(2)
Deleting: 0x7fc741c000e0(2)
于 2013-09-12T16:00:35.110 回答