MirkoBanchi
MirkoBanchi

Reputation: 2253

Autogenerated default move constructor with declared destructor

C++11 Standard specifies that auto generated move constructors should not be generated for classes declaring destructors, but the following code snippet builds and runs correctly:

#include <iostream>

class C
{
public:
    ~C() { std::cout << "Called C:~C" << std::endl; }

private:
    std::string v;
};


int main()
{
    C c1;
    C c2 = std::move(c1);

    return 0;
}

I can build with clang 4.2.1 and gcc 4.4.3. Am i missing something?

Upvotes: 1

Views: 77

Answers (2)

Slava
Slava

Reputation: 44268

Brian's answer already explains why your code compiles. To properly check that move ctor is supressed just put a non copyable object into your class, for example std::unique_ptr:

class C
{
public:
    ~C() { std::cout << "Called C:~C" << std::endl; }

private:
    std::string v;
    std::unique_ptr<char> p;
};

Now gcc 5.1.0 produces this error:

error: use of deleted function ‘C::C(const C&)’ C c2 = std::move(c1);

Upvotes: 3

Brian Bi
Brian Bi

Reputation: 119392

The initialization uses the implicitly defined copy constructor. In general a move will always fall back to a copy when the move constructor or move assignment operator cannot be used for some reason, since the copy constructor and copy assignment operator are always declared (although they can be deleted under some circumstances).

Upvotes: 4

Related Questions