什么是复制精度,它如何优化复制和交换惯用语? [英] What is copy elision and how does it optimize the copy-and-swap idiom?

查看:493
本文介绍了什么是复制精度,它如何优化复制和交换惯用语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读复制和互换



我试过阅读Copy Elision上的一些链接,但无法弄清楚它的含义。可以有人请解释这个优化是什么,特别是下面的文本是什么意思


这不仅仅是为了方便,事实上优化。如果参数绑定到一个左值(另一个非const对象),则在创建参数时自动创建对象的副本。但是,当s绑定到一个右值(临时对象,立即数)时,副本通常会被省略,这会保存对副本构造函数和析构函数的调用。在赋值运算符的早期版本中,参数被接受为const引用,当引用绑定到右值时,不会发生复制elision。这会导致创建和销毁额外的对象。



解决方案

副本。理论上,当你写一行如:

  CLASS c(foo 

编译器必须调用复制构造函数将foo / p>

复制elision是一种跳过调用复制构造函数的技术,以便不支付开销。



例如,编译器可以安排foo将直接构造它的返回值到c。



这是另一个例子。让我们假设你有一个函数:

  void doit(CLASS c); 

如果用实际参数调用它,编译器必须调用拷贝构造函数,参数不能修改:

  CLASS c1; 
doit(c1);

但现在考虑一个不同的例子,假设你像这样调用你的函数:

  doit(c1 + c1); 

operator +将必须创建一个临时对象而不是在调用doit()之前调用复制构造函数,编译器可以传递由operator +创建的临时,并将其传递给doit()。


I was reading Copy and Swap.

I tried reading some links on Copy Elision but could not figure out properly what it meant. Can somebody please explain what this optimization is, and especially what is mean by the following text

This is not just a matter of convenience but in fact an optimization. If the parameter (s) binds to a lvalue (another non-const object), a copy of the object is made automatically while creating the parameter (s). However, when s binds to a rvalue (temporary object, literal), the copy is typically elided, which saves a call to a copy constructor and a destructor. In the earlier version of the assignment operator where the parameter is accepted as const reference, copy elision does not happen when the reference binds to a rvalue. This results into an additional object being created and destroyed.

解决方案

The copy constructor exists to make copies. In theory when you write a line like:

CLASS c(foo());

The compiler would have to call the copy constructor to copy the return of foo() into c.

Copy elision is a technique to skip calling the copy constructor so as not to pay for the overhead.

For example, the compiler can arrange that foo will directly construct it's return value into c.

Here's another example. Let's say you have a function:

void doit(CLASS c);

If you call it with an actual argument, the compiler has to invoke the copy constructor so that the original parameter cannot be modified:

CLASS c1;
doit(c1);

But now consider a different example, let's say you call your function like this:

doit(c1 + c1);

operator+ is going to have to create a temporary object (an rvalue). Instead of invoking the copy constructor before calling doit(), the compiler can pass the temporary that was created by operator+ and pass that to doit() instead.

这篇关于什么是复制精度,它如何优化复制和交换惯用语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆