为什么复制构造函数不在这里? [英] Why isn't the copy constructor elided here?

查看:132
本文介绍了为什么复制构造函数不在这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我使用gcc with -O2 。)

(I'm using gcc with -O2.)

这似乎是一个简单的机会,elide因为没有副作用访问 bar中的字段的值 foo ;但是复制构造函数 被调用,因为我得到输出 meep meep!

This seems like a straightforward opportunity to elide the copy constructor, since there are no side-effects to accessing the value of a field in a bar's copy of a foo; but the copy constructor is called, since I get the output meep meep!.

#include <iostream>

struct foo {
  foo(): a(5) { }
  foo(const foo& f): a(f.a) { std::cout << "meep meep!\n"; }
  int a;
};

struct bar {
  foo F() const { return f; }
  foo f;
};

int main()
{
  bar b;
  int a = b.F().a;
  return 0;
}


推荐答案

12.8 / 15中描述的复制ctor elision的法律案例:

It is neither of the two legal cases of copy ctor elision described in 12.8/15:

返回值优化(其中从函数返回自动变量,并将该自动变量复制到返回值通过在返回值中直接构造自动化来消除)。 f 不是自动变量。

Return value optimisation (where an automatic variable is returned from a function, and the copying of that automatic to the return value is elided by constructing the automatic directly in the return value) - nope. f is not an automatic variable.

临时初始化程序构造临时和复制它,临时值直接构造到目标) - nope f 也不是临时的。 bF()是一个临时的,但它不会被复制到任何地方,它只是有一个数据成员访问,所以当你出来

Temporary initializer (where a temporary is copied to an object, and instead of constructing the temporary and copying it, the temporary value is constructed directly into the destination) - nope f is not a temporary either. b.F() is a temporary, but it isn't copied anywhere, it just has a data member accessed, so by the time you get out of F() there's nothing to elide.

因为没有复制ctor elision苹果的法律案例,以及复制 f F()的返回值影响程序的可观察行为,标准禁止它被省略。如果你用一些不可观察的活动替换了打印,并检查了程序集,你可能会看到这个拷贝构造函数被优化了。但是,这将是在as-if规则下,而不是在复制构造函数elision规则下。

Since neither of the legal cases of copy ctor elision apples, and the copying of f to the return value of F() affects the observable behaviour of the program, the standard forbids it to be elided. If you got replaced the printing with some non-observable activity, and examined the assembly, you might see that this copy constructor has been optimised away. But that would be under the "as-if" rule, not under the copy constructor elision rule.

这篇关于为什么复制构造函数不在这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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