1

As per the cpp reference cpp-ref, compiler does not generate a default move constructor if we have a user defined destructor.

Code snippet:

 class General
{
public:
    ~General();
    General();
    void testInitList();
};

int main(int argc, char **argv) {
    General b(std::move(General()));
    General g = std::move(b);
    g.testInitList();
    return 0;
}

The code compiles implying that the compiler generated a default move constructor. The code was compiled using gcc version 5.4.0.

Could someone explain why the compiler generated a move constructor and move assignment operator in this case despite have a destructor?

Best, Rahul

5
  • First, it compiled. Second, i had print statements in constructor and destructor. Only one constructor statement was printed where as multiple destructor statements were printed. Commented Jun 16, 2019 at 1:28
  • 1
    You don't define a copy constructor, that's why you don't have enough printings. Commented Jun 16, 2019 at 1:30
  • hmm. Okay let me try. Commented Jun 16, 2019 at 1:31
  • Yes, you are right. Thank you so much for the help Commented Jun 16, 2019 at 1:33
  • Does this answer your question? When does compiler not generate move constructor and move assignment? Commented Jun 26, 2023 at 5:29

1 Answer 1

2

When there's no move constructor or assignment operator, no move is performed. std::move doesn't perform the move. It just casts its argument to indicate that a move may be performed if possible. If not possible, then there's no move and using std::move does nothing.

Sign up to request clarification or add additional context in comments.

3 Comments

I had print statements in constructor and destructor. Only one constructor statement was printed where as multiple destructor statements were printed. It implies that the object was indeed moved. Output - Creating General Destroying General Destroying General Destroying General
Understood where I was making the mistake. Thank you so much Nikos.
@RGs Your code calls the default constructor and the implicitly defined copy constructor. So yes, only one will be printed. Define a copy constructor and print something there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.