What are best practices in C++ when the copy/move constructors are called with the object itself?
For example:
#include <iostream>
using namespace std;
struct Foo{
Foo( const Foo& foo ) { cout << foo.val << std::endl; };
int val;
};
int main()
{
Foo f = Foo(f);
Foo g(g);
Foo h{h};
return 0;
}
This is all legal C++, though some compilers will warn you about it.
It is commonly advised that copy assignment operators check for self-assignment. But what about self-copy construction?
Foo f = Foo(f);invokes undefined behaviour, so it's meaningless anyway.aandband calla = b;then typically you wouldnt check whethera == bbefore. On the other handFoo g(g);isnt happening that easily without being noticedFoo h{h};is wrong, but its a different oneval