标准C ++ 11是否保证传递给函数的临时对象在函数调用之前已创建? [英] Does standard C++11 guarantee that temporary object passed to a function will have been created before function call?

查看:119
本文介绍了标准C ++ 11是否保证传递给函数的临时对象在函数调用之前已创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准C ++ 11保证在开始执行函数之前已经创建了所有3个临时对象?



即使临时对象传递为:


  1. 物件

  2. rvalue-reference

  3. 对象

解决方案

[intro.execution] / 16


当调用函数是inline),与任何参数
表达式相关联的每个
值计算和副作用或者指定被调用的
函数的后缀表达式在执行每个表达式之前被排序,或
在被调用函数的正文中的语句。



Does standard C++11 guarantee that all 3 temporary objects have been created before the beginning performe the function?

Even if temporary object passed as:

  1. object
  2. rvalue-reference
  3. passed only member of temporary object

http://ideone.com/EV0hSP

#include <iostream>
using namespace std;

struct T { 
    T() { std::cout << "T created \n"; }
    int val = 0;
    ~T() { std::cout << "T destroyed \n"; }
};

void function(T t_obj, T &&t, int &&val) {
    std::cout << "func-start \n";
    std::cout << t_obj.val << ", " << t.val << ", " << val << std::endl;
    std::cout << "func-end \n";
}

int main() {

    function(T(), T(), T().val);

    return 0;
}

Output:

T created 
T created 
T created 
func-start 
0, 0, 0
func-end 
T destroyed 
T destroyed 
T destroyed 

Working Draft, Standard for Programming Language C++ 2016-07-12: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4606.pdf

§ 5.2.2 Function call

§ 5.2.2

1 A function call is a postfix expression followed by parentheses containing a possibly empty, comma-separated list of initializer-clauses which constitute the arguments to the function.

But can be any of T created after func-start?

Or is there any way to pass arguments as g/r/l/x/pr-value so that the function started before the temporary object be created?

解决方案

[intro.execution]/16:

When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function.

这篇关于标准C ++ 11是否保证传递给函数的临时对象在函数调用之前已创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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