What#39;s the most reliable way to prohibit a copy constructor in C++?(在 C++ 中禁止复制构造函数的最可靠方法是什么?)
问题描述
有时需要在 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++ 中禁止复制构造函数的最可靠方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中禁止复制构造函数的最可靠方法是什么?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
