在声明构造函数private和= delete之间有什么区别? [英] Which is the difference between declaring a constructor private and =delete?

查看:756
本文介绍了在声明构造函数private和= delete之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想声明一个类,但我想客户端不能使用复制构造函数(或复制赋值运算符)

For example, I want to declare a class but I want the client to not be able to use the copy constructor (or copy assignment operator)

以下两个不允许使用复制构造函数:

Both of the following two does not allow the use of the copy constructor:

1。

class Track
{
public:
  Track(){};
  ~Track(){};
private:
  Track(const Track&){};
};

2。

class Track
{
public:
  Track(){};
  ~Track(){};
  Track(const Track&)=delete;
};

这些方法之一比其他方法更正确吗?是否有任何副作用?

//Does not compile with both the above ways
int main()
{
  Track l;
  Track p(l);
}


推荐答案

老的做法。构造函数仍然存在,但它是私有的,只能从另一个类成员函数中调用。

Making it private is the "old" way of doing it. The constructor still exists, but it is private, and can only be invoked from within another class member function.

= delete 删除构造函数。它不是由编译器生成的,它根本不存在。

= delete deletes the constructor. It is not generated by the compiler, and it simply will not exist.

很可能, = delete 你要什么。 (虽然有一个警告,并不是所有的编译器都支持这种语法,所以如果可移植性是一个问题...)

So most likely, = delete is what you want. (although with the caveat that not all compilers support this syntax yet, so if portability is a concern...)

这篇关于在声明构造函数private和= delete之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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