Copy elision in C++

C++Server Side ProgrammingProgramming

The Copy Elision is also known as the Copy Omission. This is one of the compiler optimization technique. It avoids the unnecessary copying of objects. Almost any current compiler uses this Copy Elision technique.

Let us see how it works by the help of one example code:

Example Code

#include <iostream>
using namespace std;
class MyClass {
   public:
      MyClass(const char* str = "\0") {  //default constructor
         cout << "Constructor called" << endl;
      }
      MyClass(const MyClass &my_cls) { //copy constructor
         cout << "Copy constructor called" << endl;
      }
};
main() {
   MyClass ob = "copy class object";
}

Output

Constructor called

Now let us discuss why the copy constructor is not called?

So when an object is being constructed, one temporary object is generated and it copies to the actual object. So we can say that internally it will be looked like this:

MyClass ob = "copy class object";

Will be working as:

MyClass ob = MyClass("copy class object");

The C++ compilers avoid this kind of overheads

raja
Published on 09-Apr-2019 09:39:10
Advertisements