禁用编译器生成的复制赋值运算符 [英] Disable compiler-generated copy-assignment operator

查看:143
本文介绍了禁用编译器生成的复制赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我写一个类(例如 class nocopy )时,是否可以完全防止复制操作符的存在?如果我没有定义一个,而有人写了一些像

When I'm writing a class (say class nocopy), is it possible to prevent the existence of the copy operator entirely? If I don't define one, and somebody else writes something like

nocopy A;
nocopy B;
A = B;

编译器将自动生成一个定义。如果我自己定义一个,我会阻止编译器自动生成,但上面的代码仍然是合法的。

the compiler will auto-generate a definition. If I define one myself, I will prevent the compiler from auto-generating, but the code above will still be legal.

我想上面的代码是非法的,生成编译时错误。

I want the code above to be illegal, and generate a compile time error. How do I do that?

推荐答案

只需使用 private 访问说明符,甚至不定义它。

任何试图使用它的人都会得到一个编译错误,因为它被声明为 private

You just declare a copy constructor with private access specifier and not even define it.
Anyone trying to use it will get an compile error since it is declared private.

如果有人间接使用它,您会收到一个链接错误。

If someone uses it even indirectly, you will get a link error.

但是,在C ++ 11中,您可以 显式删除特殊成员函数

However, In C++11 you can Explicitly delete special member functions.

例如:

struct NonCopyable {
    NonCopyable & operator=(const NonCopyable&) = delete;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable() = default;
};

这篇关于禁用编译器生成的复制赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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