Disable compiler-generated copy-assignment operato

2019-02-05 13:54发布

This question already has an answer here:

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?

标签: c++ class copy
3条回答
\"骚年 ilove
2楼-- · 2019-02-05 14:02

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.

You can't do anything more than that in C++03.

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

Eg:

struct NonCopyable {
    NonCopyable & operator=(const NonCopyable&) = delete;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable() = default;
};
查看更多
干净又极端
3楼-- · 2019-02-05 14:08

If you inherit from boost::noncopyable you will get a compile time error when the copy constructor is attempted. I have found that using this the error messages (with MSVC) are useless, since they generally don't point to the line that caused the error. The alternative is to declare a copy-constructor private and leave it undefined, or define it with a BOOST_STATIC_ASSERT(false). If you are working with C++11 you can also delete your copy constructor:

class nocopy
{
    nocopy( nocopy const& ) = delete;
};
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-05 14:10

The usual way is to declare the copy constructor and the assignment operator to be private, which causes compilation errors, like Als explained.

Deriving from boost::noncopyable will do this job for you.

查看更多
登录 后发表回答