C ++ Auto create move constructor with user declared destructor?

According to cppreference and this answer , C ++ should not automatically generate a move constructor if there is a user-declared destructor. However, if this is done in practice with Clang, I see a constructor with automatic creation. The following code prints "is_move_constructible: 1":

#include <iostream> #include <type_traits> struct TestClass { ~TestClass() {} }; int main( int argc, char** argv ) { std::cout << "is_move_constructible: " << std::is_move_constructible<TestClass>::value << std::endl; } 

Do I not understand that "there is no user-declared destructor" or std :: is_move_constructible? I am compiling with '-std = C ++ 14' and Apple LLVM version 7.0.2 (clang-700.1.81).

+5
source share
2 answers

Types without a move constructor but with a copy constructor that accepts const T& arguments satisfy std::is_move_constructible , and the implicitly declared copy constructor is of the form T::T(const T&) .

If the implicitly declared copy constructor is deleted, std::is_move_constructible not executed, as shown below.

 #include <iostream> #include <type_traits> struct TestClass { ~TestClass() {} TestClass(const TestClass&) = delete; }; int main( int argc, char** argv ) { std::cout << "is_move_constructible: " << std::is_move_constructible<TestClass>::value << std::endl; } 
+8
source

For C ++ 11 code, the accepted answer by @Alper is fine. Please note that from the point of view of Clang 3.7 (I donโ€™t know which version of Apple that matches, of course, you can find out) using -std=c++1z -Wdeprecated , you will create the following

 warning: definition of implicit copy constructor for 'TestClass' is deprecated because it has a user-declared destructor [-Wdeprecated] ~TestClass() ^ 

Live example

The relevant part of the C ++ 1z Standard N4567 project is

12.8 Copying and moving class objects [class.copy]

7 If the class definition does not explicitly declare the copy constructor, the implicit one is declared implicitly. If a class definition declares a move constructor or a move carry operator, an implicitly declared copy constructor is defined as deleted; otherwise, it is defined as default (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor .

Obsolete means that the future Standard may stop generating an implicit copy constructor in case of a user-declared destructor. It is best to change your code today so as not to rely on obsolete behavior (i.e., in this case, making the instance behavior of your class explicit).

+2
source

Source: https://habr.com/ru/post/1242429/


All Articles