C++ 返回从另一个成员函数调用的常量引用的函数
我知道返回常量引用有时会引起麻烦,就像本文中接受的答案一样。 但是,我不确定以下使用const reference和隐式this指针返回的对象是否总是安全的C++ 返回从另一个成员函数调用的常量引用的函数,c++,reference,C++,Reference,我知道返回常量引用有时会引起麻烦,就像本文中接受的答案一样。 但是,我不确定以下使用const reference和隐式this指针返回的对象是否总是安全的 class foo { private: std::vector<double> vec; public: const std::vector<double>& Get_vec() const { return vec; } void
class foo
{
private:
std::vector<double> vec;
public:
const std::vector<double>& Get_vec() const
{
return vec;
}
void some_method()
{
const std::vector<double> & vec2 = Get_vec(); // this->Get_vec
// do something with vec2
}
}
class-foo
{
私人:
std::vec;
公众:
常量std::vector&Get_vec()常量
{
返回向量;
}
使某些方法无效()
{
const std::vector&vec2=Get_vec();//此->Get_vec
//用vec2做点什么
}
}
这句话
const std::vector<double> & vec2 = Get_vec();
const std::vector&vec2=Get_vec();
相当于
const std::vector<double> & vec2 = vec;
const std::vector&vec2=vec;
在类的方法中使用对类的数据成员的引用没有任何问题(我指的是方法void some_method()
)。在任何情况下,对其方法内对象的数据成员的引用的生存期都比对象本身的生存期短。接受的答案指出,这可能导致问题的唯一方法是调用方存储引用,而不是复制字符串,并在对象销毁后尝试使用它。那么,除非你打算摧毁这个物体,否则有什么问题?