Copy elision in C++
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.
1 #include <iostream>
2 using namespace std;
3
4 class B
5 {
6 public:
7 B(const char* str = "\0") //default constructor
8 {
9 cout << "Constructor called" << endl;
10 }
11
12 B(const B &b) //copy constructor
13 {
14 cout << "Copy constructor called" << endl;
15 }
16 };
17
18 int main()
19 {
20 B ob = "copy me";
21 return 0;
22 }
The output of above program is: Constructor called
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:
root:~$ g++ copy_elision.cpp -fno-elide-constructors
root:~$ ./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.
Reference: http://en.wikipedia.org/wiki/Copy_elision
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 11:13:29
最新文章
- MAC破解软件
- 使用requestAnimationFrame做动画效果一
- HDU2929 Bigger is Better[DP 打印方案 !]
- 我所经历的JS性能优化
- 内容与Tag
- 18)Java八股文名词
- VSFTPD全攻略(/etc/vsftpd/vsftpd.conf文件详解)
- 设计模式之Builder模式
- java获取当前月第一天和最后一天,上个月第一天和最后一天
- JavaBean个人总结
- 安装ArchLinux的参考分区方案
- Serializable在C#中的作用——.net中的对象序列化
- The List ADT
- java的poi技术读取和导入Excel实例
- JavaScrip 入门第一课
- 查看iis对应w3wp.exe显示的进程ID号
- Android -- taskAffinity
- Python 的 Numpy 库
- 精《Linux内核精髓:精通Linux内核必会的75个绝技》一HACK #4 如何使用Git
- php -- 魔术方法 之 对象输出 : __toString()
热门文章
- APP 自动化之appium元素定位(三)
- Git基本教程
- 手把手从0到1:搭建Kubernetes集群
- Linux usb 3. Host 详解
- 【JAVA】笔记(5)--- final;抽象方法;抽象类;接口;解析继承,关联,与实现;
- C++概述及知识点总结
- [hdu6595]Everything Is Generated In Equal Probability
- maven私服-仓库图
- docker 启动报错:Docker.Core.Backend.BackendException: Error response from daemon: open \\.\pipe\docker_e
- 洛谷 P7155 [USACO20DEC] Spaceship P(dp)