通过引用返回std :: vector导致分段错误 [英] Returning a std::vector by reference caused segmentation fault

查看:87
本文介绍了通过引用返回std :: vector导致分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,可以创建一个很大的std :: vector.返回此向量时,由于其大小,我不想再次复制它.因此,我想返回对该向量的引用.但是,这样做给我带来了细分错误.为什么是这样?解决办法是什么?

I have a function which creates a very large std::vector. When returning this vector, I do not want to copy it again, due to its size. Therefore, I want to return a reference to that vector. However, doing so gives me a segmentation fault. Why is this? What is the solution?

这是我的代码:

std::vector<int>& Foo()
{
    std::vector<int> x(100000, 50);
    return x;
}

int main()
{
    std::vector<int> y = Foo();
    return 0;
}

推荐答案

您的向量是局部变量.它存在于函数中,并在函数结束时销毁.

Your vector is a local variable. It exists within the function and is destroyed when the function ends.

因此,您的参考文献悬而未决.它指的是不再存在的对象.

Consequently, your reference is dangling. It refers to an object that no longer exists.

仅按值返回;您的编译器足够聪明,可以优化无意义的副本,即使您是C ++ 11之前的版本,因此也没有移动语义.

Just return by value; your compiler is smart enough to optimise away a pointless copy, even if you are pre-C++11 and thus don't have move semantics.

这篇关于通过引用返回std :: vector导致分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆