C++ - return pointer or const reference -
i have container has vector of objects.
class container { vector<foo> objects; i want to
- have read access these objects caller
- avoid calling copy constructor
- ignore problem of accessing these objects after container goes out of scope (this never happen)
based on that, seems have 2 choices getter method. either return const reference vector, or return pointer const vector
const vector<foo> & getref() { return objects; } const vector<foo> * getptr() { return &objects; } of course, if i'm caller, need make sure not call copy constructor when iterate. i'd this
for (const foo & f : getref()) and not
for (foo f : getref()) now, should return const reference? or pointer const? what's benefits , drawbacks?
a reference more robust. can't accidentally call delete on it.
Comments
Post a Comment