什么是复制精度和返回值优化? [英] What are copy elision and return value optimization?

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

问题描述

什么是复制精密?什么是(命名)返回值优化?他们暗示什么?

What is copy elision? What is (named) return value optimization? What do they imply?

在什么情况下会发生?有什么限制?

In what situations can they occur? What are limitations?

  • If you were referenced to this question, you're probably looking for the introduction.
  • For a technical overview, see the standard reference.
  • See common cases here.

推荐答案

简介



有关技术概述 - 请跳至此页answer

对于发生复制错误的常见情况 - 跳过

For common cases where copy elision occurs - skip to this answer.

复制elision是由大多数编译器实现的优化,以防止在某些情况下产生额外的(可能昂贵的)副本。它使得通过价值返回或通过值在实践中可行(限制适用)。

Copy elision is an optimization implemented by most compilers to prevent extra (potentially expensive) copies in certain situations. It makes returning by value or pass-by-value feasible in practice (restrictions apply).

这是唯一的优化形式规则 - 即使复制/移动对象具有副作用,也可应用复制精确

It's the only form of optimization that elides (ha!) the as-if rule - copy elision can be applied even if copying/moving the object has side-effects.

以下示例摘自维基百科

struct C {
  C() {}
  C(const C&) { std::cout << "A copy was made.\n"; }
};

C f() {
  return C();
}

int main() {
  std::cout << "Hello World!\n";
  C obj = f();
}

根据编译器&设置,以下输出都有效

Depending on the compiler & settings, the following outputs are all valid:


Hello World!

已复制。

已复制。

Hello World!
A copy was made.
A copy was made.








Hello World!

已复制。

Hello World!
A copy was made.








Hello World!

Hello World!

这也意味着可以创建更少的对象,所以你也不能依赖于特定的数字的析构函数。你不应该在复制/移动构造函数或析构函数中有重要的逻辑,因为你不能依赖它们被调用。

This also means fewer objects can be created, so you also can't rely on a specific number of destructors being called. You shouldn't have critical logic inside copy/move-constructors or destructors, as you can't rely on them being called.

如果调用复制或移动构造函数必须仍然存在并且必须可访问。这确保复制精确不允许复制通常不可复制的对象,例如。因为他们有一个私有或删除的复制/移动构造函数。

If a call to a copy or move constructor is elided, that constructor must still exist and must be accessible. This ensures that copy elision does not allow copying objects which are not normally copyable, e.g. because they have a private or deleted copy/move constructor.

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

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