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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With