How to use a object whose copy constructor and cop

2019-02-19 00:07发布

问题:

In reading TCPL, I got a problem, as the title refered, and then 'private' class is:

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

the using code is:

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

and I want to execute such operations:

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

although, these code are come from TCPL, but I still can not got the solution... Can anybody help me, appreciate.

回答1:

As its name suggests, the Unique_handle isn't meant to be copied. Its implementation ensures it by disabling the copy constructor and copy assignment operator.

One solution for multiple instances having access to a Unique_handle is holding a pointer to it, and copying the pointer. Then multiple instances of Y point to the same unique handle.

Take care, however, to manage resources properly in this case.



回答2:

The example you're looking at in Stroustrup's book is demonstrating how the designer of a class can explicitly prevent copying or assignment of objects of that class.

The class is intentionally making it so your code can't do what you're trying to do (presumably because the class won't function properly or copying otherwise doesn't make sense). If you want to be able to copy objects of that class, you'll need to redesign the class.

Some other options you might have (which also might not make sense, but that depends on what your really doing) - pass around pointers to references to the object instead of copying.



回答3:

Usually, the idiom of making your copy constructor and assignment operator private (and unimplemented) implies that the original author of the class specifically did not want this object to be copyable.



回答4:

you shouldn't try to copy it. But having said that.... you can memcpy it. Only reason you'd do that is that you know what your doing, you know the consequences, etc etc. Its generally stepping out of the bounds of whats generally acceptable. But you might want to do something a bit ninja.



回答5:

I have googled my question, and find a way to construct such a object:

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

but it seems wrong, then how can I define such a object outside?

Anyway, thank you for all of your concern.



回答6:

You can use a shared_ptr to share the object:

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

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

It's as simple as that.

If you don't want shared ownership, you can use boost::scoped_ptr or the newly created std::unique_ptr if you have access to it, and then implement the CopyConstructor and AssignmentOperator yourself, taking care of their semantics.