dimanche 2 février 2020

What is the name of this C++ compiler optimization, and how does it work?

I'm trying to learn about resource management in C++, and in my studies I've encountered an interesting optimization. Basically, when initializing an object on the stack with a copy constructor where the object is an rvalue Object (is it rvalue?), instead of calling the constructor and then calling the move constructor, the compiler simply calls the original Object's constructor.

Object c(Object(1)); // This is the same as Object c(1);
Object c(Object(Object(Object(Object(Object(1)))))); // This is also the same as Object c(1);
Expected flow:
1. Object(1) calls the constructor and creates a nameless Object that will be removed as soon as it's created.
2. ```c``` notices this is an rvalue, and calls the move constructor.
3. Destructor for Object(1) is called.
Actual flow:
1. c(1) is called.

This is smart, but.. How? What's the mechanism behind this trick? This works even if the constructor for Object accepts pointers and many arguments.

Aucun commentaire:

Enregistrer un commentaire