C++ returning collection by value
I want to make my collection immutable outside of my class.
from this:
public:
vector<int>& getValues(){
retur开发者_JAVA技巧n values;
}
private:
vector <int>& values;
to this:
public:
vector<int> getValues(){
return values;
}
private:
vector <int>& values;
Will it work fine?
It will work, but you would be better off returning a const reference:
const vector<int> & getValues() const {
return values;
}
Also, storing a reference in a class is often (not always) a mistake. You probably want a value, or possibly a pointer.
Yes, but it might have a negative impact on performance, if the collection is large, and the function is called often. What's wrong with just returning a vector<int> const&
(and declaring getValues()
const
)?
Also, I'm wondering about the fact that your member is a reference. Members should rarely be references.
public:
vector<int> getValues(){
return values;
}
private:
vector <int>& values;
Cannot possibly work as is, what is the reference to your vector actually referencing? Unless you're not showing all code here, it's not gonna work.
Just have a vector<int> values;
instead.
Yes, you can do that, but this is not necessarily what you want.
By doing this, your getValues method will make a copy of the vector. This will take some time (depending on the size of the vector).
If you are sure that the vector is not frequently changed, why not return a const reference, like this:
const vector<int> &getValues() {return values;}
return a pair
of const_iterators
, then the callee is abstracted from the underlying container too...
e.g.
typedef std::vector<int> vector_type;
public:
typedef std::pair<vector_type::const_iterator, vector_type::const_iterator> range;
range getValues() const
{
return range(values.begin(), values.end());
}
private:
vector_type values;
精彩评论