问题描述
有时需要在 C++ 类中禁止复制构造函数,以便类变为不可复制".当然,operator=
应该同时禁止.
Sometimes it's necessary to prohibit a copy constructor in a C++ class so that class becomes "non-copyable". Of course, operator=
should be prohibited at the same time.
到目前为止,我已经看到了两种方法来做到这一点.方法一是将方法声明为私有,不实现:
So far I've seen two ways to do that. Way 1 is to declare the method private and give it no implementation:
class Class {
//useful stuff, then
private:
Class( const Class& ); //not implemented anywhere
void operator=( const Class& ); //not implemented anywhere
};
方法 2 是将方法声明为私有并赋予它空"实现:
Way 2 is to declare the method private and give it "empty" implementation:
class Class {
//useful stuff, then
private:
Class( const Class& ) {}
void operator=( const Class& ) {}
};
IMO 第一个更好 - 即使有一些意外的原因导致从同一个类成员函数调用复制构造函数,稍后也会出现链接器错误.在第二种情况下,直到运行时才会注意到这种情况.
IMO the first one is better - even if there's some unexpected reason that leads to the copy constructor being called from the same class member function there'll be a linker error later on. In the second case this scenario will be left unnoticed until the runtime.
第一种方法有什么严重的缺点吗?有什么更好的方法,为什么?
Are there any serious drawbacks in the first method? What's a better way if any and why?
推荐答案
第一种方法是 Boost 如何解决它 (源代码),据我所知,没有任何缺点.事实上,链接器错误是该方法的一大优势.您希望错误发生在链接时,而不是发生在您的客户端正在执行您的代码并且它突然崩溃时.
The first method is how Boost solves it (source code), as far as I know, there's no drawbacks. In fact, the linker errors are the big advantage of that method. You want the errors to be at link time, not when your client is executing your code and it suddenly crashes.
如果您正在使用 Boost,您可以节省一些打字的时间.这与您的第一个示例相同:
In case you are using Boost, you can save yourself some typing. This does the same as your first example:
#include <boost/utility.hpp>
class Class : boost::noncopyable {
// Stuff here
}
这篇关于在 C++ 中禁止复制构造函数的最可靠方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!