gpt4 book ai didi

c++ - "It doesn’ t 对作为对象成员的引用有效在 GotW #88 中意味着什么?

转载 作者:行者123 更新时间:2023-11-30 01:06:53 26 4
gpt4 key购买 nike

Herb Sutter :

Effective Concurrency: Use Lock Hierarchies to Avoid DeadlockEffective Concurrency: Break Amdahl’s Law! » GotW #88: A Candidate For the “Most Important const” 2008-01-01 by Herb Sutter A friend recently asked me whether Example 1 below is legal, and if so what it means. It led to a nice discussion I thought I’d post here. Since it was in close to GotW style already, I thought I’d do another honorary one after all these years… no, I have not made a New Year’s Resolution to resume writing regular GotWs. :-)

JG Questions Q1: Is the following code legal C++?

// Example 1

string f() { return "abc"; }

void g() {
const string& s = f();
cout << s << endl; // can we still use the "temporary" object?
}

A1: Yes. This is a C++ feature… the code is valid and does exactly what it appears to do.

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by f() lives until the closing curly brace. (Note this only applies to stack-based references. It doesn’t work for references that are members of objects.)

本来我觉得最后一句的意思是:

class A 
{
public:
int x;
A(const int& x_)
{
x = x_;
}
};

int main()
{
A a(1); // assign lvalue to const int&
std::cout << a.x;
}

然而,它显然工作正常。

那么,“它不适用于作为对象成员的引用”是什么意思?

最佳答案

这意味着如果你这样做:

string f() { return "abc"; }

struct foo {
string const & _s;
foo() : _s(f()) {}
};

它不会延长从 f 返回的临时对象的生命周期。引用 _s 将悬空。

延长临时对象的生命周期是具有自动存储持续时间的引用的一个属性。 IE。函数范围内的局部变量。

关于c++ - "It doesn’ t 对作为对象成员的引用有效在 GotW #88 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com