Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a 'read-only' copy of a vector

Tags:

I have a class which has a private attribute vector rectVec;

class A { private:    vector<Rect> rectVec; }; 

My question is how can I return a 'read-only' copy of my Vector? I am thinking of doing this:

class A { public:   const vect<Rect>& getRectVec() { return rectVect; } } 

Is that the right way? I am thinking this can guard against the callee modify the vector(add/delete Rect in vector), what about the Rect inside the vector?

like image 406
michael Avatar asked Mar 17 '10 20:03

michael


People also ask

Does returning a vector copy?

The return by value is the preferred method if we return a vector variable declared in the function. The efficiency of this method comes from its move-semantics. It means that returning a vector does not copy the object, thus avoiding wasting extra speed/space.

How do you declare a return in a vector?

In C++11, this is the preferred way: std::vector<X> f(); That is, return by value. With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.

How do I remove content from a vector file?

All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

Does vector insert make a copy?

If you dereference the pointer and push the result onto a std::vector<T> , then a copy of the object is made. Collections always make copies.


1 Answers

That is the right way, although you'll probably want to make the function const as well.

class A { public:   const vect<Rect>& getRectVec() const { return rectVect; }                            }; 

This makes it so that people can call getRectVec using a const A object.

like image 144
Peter Alexander Avatar answered Oct 23 '22 13:10

Peter Alexander