Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move temporary object without std::move [duplicate]

Move constructor of class accepts rvalue reference which can be reference to temporary object. So, i have temporary object and appropriate move constructor which can accept reference to temporary object, but move constructor does not called. What`s wrong?

    //g++  5.4.0

#include <iostream>

class foo
{
    int data;
public:
    foo(int v) : data(v) {std::cout << "foo(int)\n";}

    foo(foo&& f)
    {
        std::cout << "moved\n";
    }

    void print()
    {
        std::cout << data;
    }
};

void acceptTmp(foo f)
{
    f.print();
}

int main()
{
    foo f1 = foo(100);
    f1.print();
    acceptTmp(foo(200)); //also does not move
}
like image 913
Kri Avatar asked Jan 02 '23 21:01

Kri


1 Answers

What`s wrong?

Nothing is wrong, except for your expectation that the move constructor would be called.

Prior to C++17, the temporary object would indeed be moved into the argument from the point of view of the abstract machine. However, the standard allows the move to be elided by the compiler, by constructing the temporary directly in place of the object where it would be moved into. You cannot rely on the side-effects of the move constructor to occur.

Post C++17, there is no temporary object or move involved. The standard guarantees that the argument is constructed in place.


The lack of a move is a good thing. Moving an object is potentially slower than not moving it.

like image 154
eerorika Avatar answered Jan 16 '23 05:01

eerorika