C++ 返回对向量成员变量的引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8384234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:29:07  来源:igfitidea点击:

Return reference to a vector member variable

c++vectorreferenceconst

提问by arjacsoh

I have a vector as member in a class and I want to return a reference to it through a getVector() function, so as to be able to modify it later. Isn't it better practice the function getVector() to be const? However I got an error “qualifiers dropped in binding reference of type…” in the following code. What should be modified?

我有一个向量作为类中的成员,我想通过 getVector() 函数返回对它的引用,以便以后能够修改它。将函数 getVector() 设为 const 不是更好吗?但是,我在以下代码中收到错误“限定符被丢弃在类型的绑定引用中...”。应该修改什么?

class VectorHolder
{
public:
VectorHolder(const std::vector<int>&);
std::vector<int>& getVector() const;

private:
std::vector<int> myVector;

};

std::vector<int> &VectorHolder::getVector() const
{
return myVector;
}

回答by Nawaz

Since it is a constmember function, the return type cannot be non-const reference. Make it const:

由于是const成员函数,返回类型不能是非常量引用。让它const

const std::vector<int> &VectorHolder::getVector() const
{
   return myVector;
}

Now it is okay.

现在没事了。

Why is it fine? Because in a constmember function, the every member becomes constin such a way that it cannot be modified, which means myVectoris a constvector in the function, that is why you have to make the return type constas well, if it returns the reference.

为什么没事?因为在const成员函数中,每个成员都以无法修改的方式变为const,这意味着函数中myVectorconst向量,这就是为什么const如果返回引用,则还必须创建返回类型。

Now you cannotmodify the sameobject. See what you can do and what cannot:

现在您不能修改同一个对象。看看你能做什么,不能做什么:

 std::vector<int> & a = x.getVector();       //error - at compile time!

 const std::vector<int> & a = x.getVector(); //ok
 a.push_back(10);                            //error - at compile time!

 std::vector<int>  a = x.getVector();        //ok
 a.push_back(10);                            //ok

By the way, I'm wondering why you need such VectorHolderin the first place.

顺便说一句,我想知道你为什么首先需要这样VectorHolder的东西。

回答by justin

it's not unusual to declare both const and mutable variants, like so:

声明 const 和 mutable 变体并不罕见,如下所示:

std::vector<int>& VectorHolder::getVector() {
  return myVector;
}
const std::vector<int>& VectorHolder::getVector() const {
  return myVector;
}

the underlying problem with your program is that you return a non-const reference from a const method.

您程序的潜在问题是您从 const 方法返回了一个非常量引用。

std::vector<int>& VectorHolder::getVector() const {
  return myVector; // << error: return mutable reference from const method
}

so you make it const using this form:

所以你使用这种形式使它成为常量:

const std::vector<int>& VectorHolder::getVector() const {
  return myVector; // << ok
}

and when this is in a non const method or the client holds a non-const reference, then you can legally use a non-const method:

并且当这是在非常量方法中或客户端持有非常量引用时,那么您可以合法地使用非常量方法:

std::vector<int>& VectorHolder::getVector() {
  return myVector; // << ok
}

finally, you could return a value (in some cases):

最后,您可以返回一个值(在某些情况下):

std::vector<int> VectorHolder::getVector() const {
  return myVector; // << ok
}

because the copy requires no mutation and provides no exposure to the internal data.

因为副本不需要突变并且不提供对内部数据的暴露。

so you will end up declaring both variants quite often.

所以你最终会经常声明这两种变体。

the results of declaring both are:

声明两者的结果是:

VectorHolder m;
const VectorHolder c;

m.getVector().size(); // << ok
c.getVector().size(); // << ok - no mutation

m.getVector().push_back(a); // << ok
c.getVector().push_back(a); // << error: attempt to mutate const reference because the const vector is returned

so it all works out nicely (apart from the redundancy of the methods).

所以一切都很好(除了方法的冗余)。

回答by Some programmer dude

The function getVectorcan be declared as const. It returns a reference that can be modified, so while the actual function doesn't modify anything in the class, the caller will be able to modify internal data.

该函数getVector可以声明为const. 它返回一个可以修改的引用,因此虽然实际函数不会修改类中的任何内容,但调用者将能够修改内部数据。

Declare it as:

将其声明为:

std::vector<int>& getVector();

If you want a function to return a vector that can't be modified, the use the constmodifier on both the vector and the function:

如果您希望函数返回无法修改const的向量,请在向量和函数上使用修饰符:

const std::vector<int>& getVector() const;

回答by Lev

The reason is that a const member function should only return const references. This is because in a const function, every data member becomes constant.

原因是 const 成员函数应该只返回 const 引用。这是因为在 const 函数中,每个数据成员都变为常量。

Therefore you have to declare the getVector() this way:

因此,您必须以这种方式声明 getVector():

std::vector<int> &VectorHolder::getVector() const;