How to use an object whose copy constructor and copy assignment are private?

When reading TCPL, I had a problem, as indicated in the title, and then the class 'private':

class Unique_handle {
private:
    Unique_handle& operator=(const Unique_handle &rhs);
    Unique_handle(const Unique_handle &rhs);
public:
    //...
};

code used:

struct Y {
    //...
    Unique_handle obj;
};

and I want to perform the following operations:

int main()
{
    Y y1;
    Y y2 = y1;
}

although this code comes from TCPL, but I still can’t get a solution ... Someone can help me, please rate.

+3
source share
6 answers

As the name suggests, Unique_handleit is not intended for copying. Its implementation provides it by disabling the copy constructor and copy assignment operator.

, Unique_handle, . Y .

, , .

+6

, , , .

, , ( , ). , .

, ( , , ) - .

+4

, , ( ), , , .

+2

. , ..., . , , , , , .. .. . - .

+2

:

static Unique_handle * instance() {return new Unique_handle(); }

, ?

In any case, thank you for all your worries.

0
source

You can use shared_ptrto share an object:

class Y
{
public:
  Y(): mHandle(new UniqueHandle()) {}

private:
  boost::shared_ptr<UniqueHandle> mHandle;
};

It is so simple.

If you do not need co-ownership, you can use boost::scoped_ptror just created std::unique_ptrif you have access to it, and then run CopyConstructor and AssignmentOperator yourself, taking care of your semantics.

0
source

Source: https://habr.com/ru/post/1748632/


All Articles