加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C – “最重要的const”不适用于表达式?

发布时间:2020-12-16 10:10:59 所属栏目:百科 来源:网络整理
导读:根据Herb Sutter的文章 http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/,以下代码是正确的: #include iostream#include vectorusing namespace std;vectorvectorint f() { return {{1},{2},{3},{4},{5}}; }int main()
根据Herb Sutter的文章 http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/,以下代码是正确的:

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> f() { return {{1},{2},{3},{4},{5}}; }

int main()
{
    const auto& v = f();
    cout << v[3][0] << endl;
}

即,v的生存期延长到v const参考的生命周期.
事实上,根据valgrind的说法,这可以很好地用gcc和clang编译而且没有泄漏.

但是,当我改变主要功能时:

int main()
{
    const auto& v = f()[3];
    cout << v[0] << endl;
}

它仍然编译,但valgrind警告我函数的第二行中的无效读取,因为第一行中的内存是空闲的.

这是符合标准的行为还是g(4.7.2)和clang(3.5.0-1~exp1)中的错误?

如果它符合标准,对我来说似乎很奇怪……哦.

解决方法

除了代码之外,这里没有任何错误.

第一个示例有效,因为当您将f()的结果绑定到v时,可以延长该结果的生命周期.

在第二个示例中,您不会将f()的结果绑定到任何内容,因此不会延长其生命周期.绑定到它的子对象将计数:

[C++11: 12.2/5]: 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 except: [..]

…但你没有这样做:你绑定到对象上调用成员函数(例如operator [])的结果,并且该结果不是向量的数据成员!

(值得注意的是,如果你有一个std :: array而不是std :: vector,那么the code?绝对没问题,因为数组数据存储在本地,所以元素是子对象.)

所以,你有一个悬浮引用f()的原始结果的逻辑元素,它已经超出了范围.

?抱歉可怕的初始化器,但是,好吧,责怪C.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读