How to use a object whose copy constructor and copy assignment is private?

江枫思渺然 提交于 2019-12-01 08:39:24

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.

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.

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.

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!