- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
http://www.gotw.ca/gotw/067.htm中有一个例子 int main() { double x = 1e8; //float x = 1e8; while( x >
GotW #47 The Wrong Solution "Aha," many people -- including many experts -- have said, "let's use un
Gotw 80包括以下示例: // Example 1 // #include using namespace std; class A { public: A(
在GotW article #45 , Herb 声明如下: void String::AboutToModify( size_t n, bool bMarkUnshareable /*
这个伪代码是从GotW #53获得的在副标题“一个不太好的长期解决方案”下。几个小时以来,我一直在努力理解作者在说什么,特别是与下面以“//error: potential ...”开头的评论有关,但
引用文章Gotw 54通过 HerbSutter,他解释了 “收缩以适应”的正确方法 vector 或双端队列和 完全清除 vector 或的正确方法双端队列 Can we just use cont
首先阅读 Herb 的 Sutters GotW 关于 C++11 中的 pimpl 的帖子: GotW #100: Compilation Firewalls (Difficulty: 6/10)
Herb Sutter : Effective Concurrency: Use Lock Hierarchies to Avoid DeadlockEffective Concurrency: Br
我正在阅读 typename 上的一篇旧 Guru of the Week 文章, #35 .在最后,您可以找到以下代码段: #include using std::cout; using std:
根据 Herb Sutter,http://www.gotw.ca/publications/mill18.htm建议您不要有任何公共(public)虚函数,而是从非虚拟公共(public)函数调用私
我是一名优秀的程序员,十分优秀!