user2953119
user2953119

Reputation:

Why isn't move constructor called?

The Standard provides an example regarding to the a move constructor. There is what it says:

A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

I was trying to run some an experiments with an example the Stadard provides:

#include <iostream>
#include <limits>


struct Y {
    Y(){ std::cout << "Y()" << std::endl; };
    Y(const Y&){ std::cout << "Y(const Y&)" << std::endl; };
    Y(Y&&){ std::cout << "Y(const Y&&)" << std::endl; };
};

Y f(int)
{
    return Y();
}

Y d(f(1)); // calls Y(Y&&)
Y e = d; // calls Y(const Y&)

int main(){ }

DEMO

But instead copy constructor was called. Why that?

Upvotes: 0

Views: 95

Answers (1)

M.M
M.M

Reputation: 141544

The copy-constructor is invoked by the line:

Y e = d;

This cannot be a move operation , because d is an lvalue. This is why you see the copy constructor call in your output.

For the line Y d(f(1)), d is moved from the rvalue f(1) (which was in turn moved from Y()), however copy elision means that the output of both of these move-constructors may be suppressed.

Upvotes: 2

Related Questions