const引用临时对象的成员 [英] const reference to member of temporary object

查看:150
本文介绍了const引用临时对象的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是已知C ++的特性,const引用扩展从函数返回的临时对象的生命周期,但是使用常量引用从函数返回的临时对象的成员也可以接受?

It is known feature of C++ that a const reference extends the life time of the temporary object returned from a function, but is it acceptable to use constant reference to the member of the temporary object returned from the function?

示例:

#include <string>

std::pair<std::string, int> getPair(int n)
{
    return {std::to_string(n), n};
}

int main(int, char*[])
{
    const int x = 123456;
    const auto& str = getPair(x).first;
    printf("%d = %s\n", x, str.c_str());    
    return 0;
}

输出

123456 = 123456


推荐答案

是的,这个代码是完全可以接受的。规则,根据标准是([class.temporary]):

Yes, this code is perfectly acceptable. The rules, according to the standard are ([class.temporary]):



  1. 有两个上下文,其中临界被破坏在一个
    不同的点,而不是结束。第一个上下文
    是当调用默认构造函数来初始化
    数组的元素时。如果构造函数有一个或多个默认参数,那么在构造下一个数组元素(如果有的话)之前,在默认参数中创建的每个临时的
    破坏是

  1. There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.

第二个上下文是引用绑定到临时文件。引用绑定到的
临时绑定的引用绑定的子对象的
完整对象的临时
在参考...

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference...


正如您所看到的,

请注意,第一个 $ c>符合子对象[intro.object]:

Note that first does qualify as a subobject [intro.object]:



  1. 包含其他对象,称为子对象。一个子对象可以
    是一个成员子对象(9.2),一个基类子对象(子句10)或一个
    数组元素。不是任何其他对象
    的子对象的对象称为完整对象。


这篇关于const引用临时对象的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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