mardi 1 mars 2016

How does RVO and rvalue returned by the function work?

To understand the way how compiler selects constructor of a class, I wrote code following:

#include <iostream>

struct Widget
{
    Widget(Widget&& w){std::cout << "Move ctor" << std::endl;}
    Widget(void){std::cout << "Default ctor" << std::endl;}
    Widget(const Widget& w){std::cout << "Copy ctor" << std::endl;}
}

Widget make_widget(void) //helper function
{
    Widget w;
    return w;
}

int main(void)
{
    Widget w(make_widget());
}

According to item 25 of Effective Modern C++, compiler treats w as to be rvalue reference because of Return Value Optimization. So I expected Widget w(make_widget()) calls move constructor. but it doesn't. Furthermove, it prints only

Default

So I have no idea which version of constructor was called. Then I also tried to return rvalue explicitly. That is, return std::move(w) . Against my expectation considering above result, it correctly called move constructor, and printed

Default
Move

It seems I'm in the maze of rvalue. Please tell me what's going on there.

Aucun commentaire:

Enregistrer un commentaire