Can I prevent a copy constructor with some exception?
-
18-06-2021 - |
質問
I will use std::map<int, A>
A
is a class and I have to prevent shallow copy,
but there are many classes like A
, so making a deep copy construct and operator is tiresome.
Since it seems that I don't have to use copy constructor and copy assignment operator,
I decide not to use them.
To prevent some mistakes, I made UnCopyable class, which has private copy constuctor and copy assignment operator, and A
inherited it.
However, there is one problem. std::map
use a copy constructor.
I don't want to save A
's pointer in the map.
What's the better solution?
解決
You could use a smart pointer like std::shared_ptr
or write a proxy class.
E.g.:
class Foo {
public:
std::string name() const;
};
typedef std::shared_ptr<Foo> SharedFoo;
or
class SharedFoo {
public:
std::string name() const { return instance->name(); }
private:
std::shared_ptr<Foo> instance;
};
他のヒント
You might think about trying C++11, which has a couple solutions to this kind of problem: std::map::emplace
which eliminates the Copyable requirement for A
, and std::move
which allows you to transfer one object into another without copying.
Also, there is a new, more explicit way to define a class as non-copyable:
A( A const & ) = delete;
It's a good time to upgrade your C++ compiler.