常量引用延长函数返回的临时对象的生命周期是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]):
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...
如您所见,突出显示的行清楚地表明对子对象的绑定(bind)引用是可以接受的,因为完整的对象也必须延长其生命周期。
请注意,first
确实有资格作为子对象 [intro.object]:
- 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/