避免使用禁用的复制构造函数进行隐式复制
假设你有一个类 NonCopyable
class NonCopyable
{
public:
NonCopyable(int n){}
~NonCopyable(){}
[...]
private:
[members...]
private:
NonCopyable( const NonCopyable& ); //disabled (no definition)
NonCopyable& operator= ( const NonCopyable& ); //disabled (no definition)
};
对于这个类,拥有它的副本是不合逻辑的,因此复制构造函数和赋值运算符被禁用。
但是,当您需要 NonCopyables 对象的向量时:
std::vector<NonCopyable> m_V;
int n;
m_V.push_back(NonCopyable(n));
在这里,您隐式调用复制构造函数。
我被教导通过使用指向这些对象的指针而不是对象本身来解决这个问题。但这在使用和性能方面都很烦人,因为您必须使用 new() 动态分配这些对象...
我的问题: 有办法解决这个问题吗?这个问题的常见解决方案是什么?
Suppose you have a class NonCopyable
class NonCopyable
{
public:
NonCopyable(int n){}
~NonCopyable(){}
[...]
private:
[members...]
private:
NonCopyable( const NonCopyable& ); //disabled (no definition)
NonCopyable& operator= ( const NonCopyable& ); //disabled (no definition)
};
For this class, it's illogical to have copies of it, thus the copy constructor and assignment operator are disabled.
However, when you need a vector of NonCopyables objects:
std::vector<NonCopyable> m_V;
int n;
m_V.push_back(NonCopyable(n));
Here, you implicitly invoke the copy constructor.
I've been taught to solve this problem by using pointers to those objects instead of the objects themselves. But this is annoying both in use and in performance, because you have to dynamically allocate those objects with new()...
My question:
Is there a way around this? What's a common solution to this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++11 有一个适用于许多不可复制类的解决方案:使类可移动(而不是可复制),并使用
emplace_back
向向量添加新元素。如果你需要用 C++03 捏造一些东西,也许你可以找到一种方法来实现“空”NonCopyable 对象的复制(并使用 Luchian 的限制此操作的想法),并且还可以找到一种方法来实现
swap< /代码>。然后你可以这样做:
C++11 has a solution that applies to many non-copyable classes: make the class movable (instead of copyable), and use
emplace_back
to add new elements to the vector.If you need to fudge something with C++03, perhaps you can find a way to implement copying of "empty" NonCopyable objects (and use Luchian's idea of restricting this operation), and also find a way to implement
swap
. Then you can do:您可以使
向量
成为该类的友元:或者您可以拥有一个指向该类的智能指针的
向量
。编辑:
我可能误解了这个问题。如果您不想要该类的副本(我最初的猜测是您不希望制作可公开访问的副本),那么您绝对应该使用智能指针。
You can make the
vector
a friend of the class:or you could have a
vector
of smart pointers to the class.EDIT:
I might have misunderstood the question. If you don't want copies of the class (my original guess was that you didn't want making copies to be publicly accessible), you should definetely use smart pointers.