Copy elision (or Copy omission) is a compiler optimization technique that avoids unnecessary copying of objects. Now a days, almost every compiler uses it. Let us understand it with the help of an example.
The output of above program is:
Why copy constructor is not called?
According to theory, when the object “ob” is being constructed, one argument constructor is used to convert “copy me” to a temporary object & that temporary object is copied to the object “ob”. So the statement
B ob = "copy me";
should be broken down by the compiler as
B ob = B("copy me");
However, most of the C++ compilers avoid such overheads of creating a temporary object & then copying it.
The modern compilers break down the statement B ob = "copy me"; //copy initialization as B ob("copy me"); //direct initialization and thus eliding call to copy constructor.
However, if we still want to ensure that the compiler doesn’t elide the call to copy constructor [disable the copy elision], we can compile the program using “-fno-elide-constructors” option with g++ and see the output as following:
aashish@aashish-ThinkPad-SL400:~$ g++ copy_elision.cpp -fno-elide-constructors aashish@aashish-ThinkPad-SL400:~$ ./a.out Constructor called Copy constructor called
If “-fno-elide-constructors” option is used, first default constructor is called to create a temporary object, then copy constructor is called to copy the temporary object to ob.
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backwards()
- Copy Constructor in C++
- When should we write our own copy constructor?
- Copy-and-Swap Idiom in C++
- When is copy constructor called?
- Ways to copy a vector in C++
- Advanced C++ | Virtual Copy Constructor
- Copy constructor vs assignment operator in C++
- Why copy constructor argument should be const in C++?
- Preventing Object Copy in C++ (3 Different Ways)
- C program to copy string without using strcpy() function
- When does compiler create default and copy constructors in C++?
- Program to copy the contents of one array into another in the reverse order
- C program to copy contents of one file to another file