什么是最可靠的方法来禁止复制构造函数在C ++? [英] What's the most reliable way to prohibit a copy constructor in C++?

查看:337
本文介绍了什么是最可靠的方法来禁止复制构造函数在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.

到目前为止,我已经看到两种方法去做。方法1是将方法声明为私有并且不给它实现:

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 ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆