在函数的出口处通过引用传递(=返回)向量 [英] passing( = returning) by reference a vector at the exit of function

查看:1074
本文介绍了在函数的出口处通过引用传递(=返回)向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是c ++ snipet合法吗?

is this c++ snipet legal?

vector<myType>& aClass::aFunction()
{
    vector<myType> aVec;

    //do stuff

    return aVec;
}

然后在另一个函数中使用它:

then use it in another function as:

vector<myType> getVec = aFunction();

基本上,我问:如果我声明 getVec 并获得对 aVec 向量数据的引用,数据是否会在 aFunction()

so basically, I am asking: if I declare getVec and get a reference to aVec vector data, will the data survive the death of aFunction() ?

推荐答案

即使编译器会让它滑脱,变量会与函数的作用域一起消失,所以你会有一个悬挂参考并有效地进入未定义的行为状态。

No even if the compiler would let it slip, the variable dies with the scope of the function, so you would have a dangling reference and effectively enter Undefined Behaviour state.

返回值,任何下降编译器将执行(N)RVO 。有一些限制,所以你应该检查你的编译器的要求。特别是如果有多个出口点。

Return by value, any descent compiler will perform (N)RVO. There are some restrictions, so you should alaways check the requirements for your compiler. Especially if there are multiple exit points. But it's best course of action and produces cleanest and fastest code.

附录:

它会生成( clang ++ g ++

luk32@debianvm:~/projects/tests$ g++ ./dangling_reference.cpp 
./dangling_reference.cpp: In function 'std::vector<int>& test()':
./dangling_reference.cpp:6:17: warning: reference to local variable 'v' returned [-Wreturn-local-addr]
     vector<int> v(10);
                 ^
luk32@debianvm:~/projects/tests$ clang++ ./dangling_reference.cpp 
./dangling_reference.cpp:7:12: warning: reference to stack memory associated with local variable 'v' returned [-Wreturn-stack-address]
    return v;

但是我建议将这些警告标记为错误,因为它们几乎总是在安全方面,我不知道如何返回引用到局部变量而不输入UB),并考虑向编译器命令添加适当的开关。例如:

However I would advise to mark those warnings as errors, as they nearly always are (by nearly I mean to be on the safe side, I don't know how to return reference to a local variable and not enter UB), and consider adding appropriate switches to the compiler commands. E.g.:

g++ -Werror=return-local-addr ./dangling_reference.cpp
clang++ -Werror=return-stack-address ./dangling_reference.cpp

IMO,这是一个很好的做法,如果你的项目足够大任何超过手工编译。

IMO, it's a good practice if your project is big enough for anything more than compiling by hand.

这篇关于在函数的出口处通过引用传递(=返回)向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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