Why does the insertion of user defined destructor require an user defined copy constructor

后端 未结 2 402
走了就别回头了
走了就别回头了 2021-01-21 02:10

The following code compiles:

#include 
#include 
#include 

using namespace std;

class container
{
public:
    conta         


        
2条回答
  •  花落未央
    2021-01-21 03:02

    The code gets compiled because buildShip() would use the move constructor automatically generated by the compiler when returning tmp. Adding user-declared destructor prevents the compiler from auto-generating one. E.g., see this or this questions. And the compiler-generated copy constructor can not be used because of the member up which is std::unique_ptr. And copy constuctor of unique_ptr is explicitly deleted.

    So this will compile, because the compiler is explicitly asked to generate the move constructor:

    class Ship
    {
    public:
        Ship(){}
        Ship(Ship&&) = default;
        ~Ship(){}
        std::unique_ptr up;
    };
    

提交回复
热议问题