Why does defining a destructor prevent defining a move constructor?

Hi,

Looking at this code:

1
2
3
4
5
class T{
public:
  ~T(){} // dtor prevents move ctor
         // copy ctor is noexcept
};


Supposedly the presence of the dtor prevents the move ctor but I tried this and works:

1
2
3
4
5
	void try_move()
	{
		T t{};
		T other{ std::move(t) };
        }


I am using VS 2017 v 15.9.7

Regards,
Juan
It will fall back to using the copy constructor if there isn't a move constructor.
But why does the presence of the destructor cause this? It says "dtor prevents move ctor" which sounds different to your reason "since there is no move ctor provided then it falls back on using the copy ctor"...
Ever heard of the rule of three/five? If you define a destructor, or a copy constructor (or move constructor) or a copy assignment operator (or move assignment operator) you probably should define all of them.

If you write a destructor, it is normally to free memory or some other non-RAII resource, in which case the implicitly defined copy constructor and move constructor will most likely not do what you want. That is why, when move constructors were added in C++11, they made the rules so that no move constructor will be generated if you explicitly define a destructor (or any of the other three mentioned above).

Ideally, the same rules should also apply to the copy constructor. The old behaviour has been deprecated since C++11, so you should no longer write code that relies on a copy constructor being automatically generated if you define a destructor, but the rules has not been changed yet in order to give people time to update their code. GCC 9 adds new warning flags (-Wdeprecated-copy-dtor) to warn about these things.
Last edited on
Thanks Peter87
closed account (E0p9LyTq)
Ever heard of the rule of three/five?

I know the question wasn't directed at me, but......I've never heard of that rule before.

Now that I have I will try to apply it. Thanks for the info. :)
Topic archived. No new replies allowed.