简体   繁体   中英

C++ How to handle copy of objects with destructor that damages the state?

I'm not sure if I've worded this correctly.

Basically, I have a class like this:

class A
{
public:
    A()
    {
        CreateHandle(&m_handle);
    }

    ~A() 
    { 
        DeleteHandle(&m_handle); 
    }

private:
    Handle m_handle;
}

And it's a member of another class:

class B
{
public:
    B(int data) : m_data(data) {} 
    /* ... */

private:
    A m_a;
    int m_data;
}

And finally I have a third class which is sort of like a container of B s:

class C
{
public:
    /* ... */
    void AddOneB(B b)
    {
        m_bs.push_back(b);
    }        

private:
    std::vector<B> m_bs;
}

Lastly, in my code where I'm creating a C instance, I would do something like this:

...
C cObj;
cObj.AddOneB( B(23) );
...

My problem is that the destructor of A actually destroys the memory that it created in it's constructor. So doing this results in my cObj getting a B with an A that it no good.

My first thought was to make the instance of A in B a std::shared_ptr , but I was wondering if there's any other, paradigm (is that the word), to handle situations like this?

I can't see how copy constructors or move constructors can help here because the destructor will be called regardless.

You need to make a choice: either A has unique ownership of the Handle , or it has shared ownership of it.

If the former, you need to make A noncopyable. For exactly the problems you present in your question. If C++11, you should make it movable:

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
}

If the latter, you need to reference count the Handle so that only one of the copies of A destroys it:

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);
        }
    }
};

Shared ownership is more expensive (and what I wrote above is not thread-safe, if that's a concern), so pick the one that makes the most definitely. Definitely you cannot have a copyable type that expresses have unique ownership - that is asking for trouble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM