[英]How is destructor called for temporary objects returned from a function in C++?
[英]C++ How to handle copy of objects with destructor that damages the state?
我不确定我的措词是否正确。
基本上,我有一个这样的课:
class A
{
public:
A()
{
CreateHandle(&m_handle);
}
~A()
{
DeleteHandle(&m_handle);
}
private:
Handle m_handle;
}
它是另一个类的成员:
class B
{
public:
B(int data) : m_data(data) {}
/* ... */
private:
A m_a;
int m_data;
}
最后,我有了第三类,有点像B
的容器:
class C
{
public:
/* ... */
void AddOneB(B b)
{
m_bs.push_back(b);
}
private:
std::vector<B> m_bs;
}
最后,在创建C
实例的代码中,我将执行以下操作:
...
C cObj;
cObj.AddOneB( B(23) );
...
我的问题是A
的析构函数实际上破坏了它在其构造函数中创建的内存。 因此,这样做会导致我的cObj
得到一个B
和一个A
,这不好。
我的第一个想法是将B
的A
实例设为std::shared_ptr
,但是我想知道是否还有其他范式(就是这个词)来处理这种情况?
我看不到复制构造函数或移动构造函数在这里有什么帮助,因为无论如何都会调用析构函数。
您需要做出选择: A
拥有Handle
唯一所有权 ,或者它拥有它的共享所有权 。
如果是前者,则需要使A
不可复制。 对于问题中出现的问题。 如果是C ++ 11,则应使其可移动:
A(const A&) = delete;
A& operator=(const A&) = delete;
A(A&& rhs) {
// transfer ownership of m_handle from rhs to this
// so that rhs doesn't destroy it
}
如果是后者,则需要引用该Handle
以便仅A
一个副本销毁它:
class A {
int* refCnt;
Handle m_handle;
public:
A()
{
CreateHandle(&m_handle);
refCnt = new int(1);
}
A(const A& rhs)
: m_handle(rhs.m_handle)
, refCnt(rhs.refCnt)
{
(*refCnt)++; // now we have an additional reference
}
~A() {
if (--*refCnt == 0) {
// only destroy if we're the LAST one
DeleteHandle(&m_handle);
}
}
};
共享所有权更加昂贵(如果担心的话,我上面写的也不是线程安全的),因此请选择最确定的所有权。 绝对不能拥有表示唯一所有权的可复制类型-这很麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.