Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to disable copy and move semantics

The following surely works but is very tedious:

T(const T&) = delete;
T(T&&) = delete;
T& operator=(const T&) = delete;
T& operator=(T&&) = delete;

I'm trying to discover the most concise way. Will the following work?

T& operator=(T) = delete;

Update

Note that I choose T& operator=(T) instead of T& operator=(const T&) or T& operator=(T&&), because it can serve both purposes.

like image 818
Lingxi Avatar asked Feb 19 '18 11:02

Lingxi


2 Answers

According to this chart (by Howard Hinnant):

meow

The most concise way is to =delete move assignment operator (or move constructor, but it can cause problems mentioned in comments).

Though, in my opinion the most readable way is to =delete both copy constructor and copy assignment operator.

like image 185
HolyBlackCat Avatar answered Sep 25 '22 23:09

HolyBlackCat


You can write a simple struct and inherit from it:

struct crippled
{
    crippled() = default;

    crippled(const crippled&) = delete;
    crippled(crippled&&) = delete;

    crippled& operator=(const crippled&) = delete;
    crippled& operator=(crippled&&) = delete;
};

Usage:

struct my_class : crippled
{

};

int main()
{
    my_class a;
    auto b = a; // fails to compile
}
like image 34
Vittorio Romeo Avatar answered Sep 23 '22 23:09

Vittorio Romeo