Search code examples
c++c++11standardsc++17

Shall we move to new way of self-assignment protection?


All

traditionally, in books on C++ and even in Core Guidelines the self-assignment protection is written as

A& A::operator=(const A& a) {
    if (&a != this) {
       ...
    }
    return *this;
}

But in modern C++ (since C++-11) we have std::addressof magic.

If I to teach students all the goodies of modern C++, shall I promote self-assignment check to be written as

A& A::operator=(const A& a) {
    if (std::addressof(a) != this) {
       ...
    }
    return *this;
}

More general question - should it be the way to go, in Core Guidelines and elsewhere?

Thoughts? Comments?


Solution

  • std::addressof is intended for generic code.

    In generic code, unary operator& could be overloaded by the type you are interacting with. And if you want the real address, that won't do.

    In non-generic code, operator& overloading is both rare and pathological. Anyone who overloads operator& on a type is going to make that type extremely weird and will have to audit every use of it anyhow.

    The use of unary operator& overloading has fallen out of favour -- even pseudo-com smart pointers have gotten out of the habit. About the only recent use I've seen is someone writing expressions that produce function objects and the like.

    Nearly pointless verbosity is not a great thing.