对未命名对象的RVO(返回值优化)是否是普遍保证的行为? [英] Is RVO (Return Value Optimization) on unnamed objects a universally guaranteed behavior?

查看:177
本文介绍了对未命名对象的RVO(返回值优化)是否是普遍保证的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题在不同方面(也限于gcc)。我的问题仅适用于未命名对象。允许返回值优化 更改可观察到的行为 的结果程序。这似乎也在标准中提到。

This question is in different aspect (also limited to gcc). My question is meant only for unnamed objects. Return Value Optimization is allowed to change the observable behavior of the resulting program. This seems to be mentioned in standard also.

但是,这个允许这是否意味着RVO 保证在每个编译器上发生。由于RVO下面的代码更改,它的可观察的行为:

However, this "allowed to" term is confusing. Does it mean that RVO is guaranteed to happen on every compiler. Due to RVO below code changes it's observable behavior:

#include<iostream>
int global = 0;
struct A {
  A(int *p) {}
  A(const A &obj) { ++ global; }
};

A foo () {  return A(0); }  // <--- RVO happens
int main () {
  A obj = foo(); 
  std::cout<<"global = "<<global<<"\n"; // prints 0 instead of 2
}

这个程序假设打印 global = 0 对于所有实现,无论编译器优化和方法大小 foo

Is this program suppose to print global = 0 for all implementations irrespective of compiler optimizations and method size of foo ?

推荐答案

根据标准,程序可以打印0,1或2. C ++ 11中的特定段落是12.8p31,开头为:

According to the standard, the program can print 0, 1 or 2. The specific paragraph in C++11 is 12.8p31 that starts with:


当满足某些标准时,允许实现省略类对象的复制/移动构造,即使复制/移动构造函数和/对象有副作用。

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.

请注意,这两个副本elisions不是一个优化, em>规则(其要求程序的行为与同一程序的行为一致,因为如果没有进行优化)。标准显式地允许实现生成不同的可观察行为,并且由程序员来决定你的程序不依赖于它(或接受所有三种可能的结果)。

Note that both copy elisions are not an optimization that falls in the as-if rule (which requires the behavior of the program to be consistent with the behavior of the same program as-if no optimization had taken place). The standard explicitly allows the implementation to generate different observable behaviors, and it is up to you the programmer to have your program not depend on that (or accept all three possible outcomes).

注2:1在任何答案中都没有提到,但它是一个可能的结果。有两个潜在的拷贝发生,从函数中的局部变量到返回的对象到 main 中的对象,编译器可以省略,一个或两个副本生成所有三种可能的输出。

Note 2: 1 is not mentioned in any of the answers, but it is a possible outcome. There are two potential copies taking place, from the local variable in the function to the returned object to the object in main, the compiler can elide none, one or the two copies generating all three possible outputs.

这篇关于对未命名对象的RVO(返回值优化)是否是普遍保证的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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