c++ - 对临时对象成员的 const 引用

标签 c++ c++11 reference constants language-lawyer

常量引用延长函数返回的临时对象的生命周期是C++的known feature,但是对函数返回的临时对象的成员使用常量引用是否可以接受?

示例:

#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]):

  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.

  2. 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...

如您所见,突出显示的行清楚地表明对子对象的绑定(bind)引用是可以接受的,因为完整的对象也必须延长其生命周期。

请注意,first 确实有资格作为子对象 [intro.object]:

  1. Objects can contain other objects, called subobjects. A subobject can be a member subobject (9.2), a base class subobject (Clause 10), or an array element. An object that is not a subobject of any other object is called a complete object.

关于c++ - 对临时对象成员的 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38226443/

相关文章:

c++ - 使用智能指针和继承构造函数的前向声明

c++ - 关于隐式删除的虚拟析构函数的错误消息是什么?

c++ - 使用 shared_from_this 时出现 std::bad_weak_ptr 异常

interface - TMS320C64x 程序员快速入门引用

c# - 更改列表中的引用值

C++ 在 switch 中使用 int 时非常奇怪的行为

c++ - 如何使用 TesseractOCR 构建 OpenCV?

c++ - FFTW编译错误c++

c++ - std::unordered_set 是否连续(如 std::vector)?

mysql - 使用groovy域类引用其他表中的字段创建mysql表