This question already has an answer here:
I wrote a simple test program to understand move semantics and return value optimization. I tested the following program in my local machine (4.4.0 linux kernel, 5.4.0 g++), with --std=c++14 flag.
g++ --std=c++14 main.cpp
The program:
#include <iostream>
using namespace std;
class Component {
public:
Component();
Component(Component& _c);
Component& operator=(Component& _c);
Component(Component&& _c);
Component& operator=(Component&& _c);
virtual ~Component() = default;
};
Component::Component() {
cout << "default constructor" << endl;
}
Component::Component(Component& _c) {
cout << "copy constructor" << endl;
}
Component& Component::operator=(Component& _c) {
cout << "copy assignment" << endl;
return *this;
}
Component::Component(Component&& _c) {
cout << "move constructor" << endl;
}
Component& Component::operator=(Component&& _c) {
cout << "move assignment" << endl;
return *this;
}
auto maker() {
Component c;
return c;
}
auto move_maker() {
Component c;
return std::move(c);
}
int main() {
auto c1 = maker();
auto c2 = move_maker();
return 0;
}
The program outputs:
default constructor
default constructor
move constructor
I understand that the second "default constructor" comes from initializing Component inside move_maker(), and the "move constructor" comes from the main function where c2 is initialized (initialized with rvalue reference). What I don't understand is why maker() along with initializing c1 outputs only "default constructor". For
Component c1 = maker();
What's going on there? Why constructor is not called? Does it have anything to do with small value optimization?
Aucun commentaire:
Enregistrer un commentaire