Suppose we have some class, say class Apple
, and wanted to store a std::vector
containing Apple
.
Should the vector contain pointers, references, or plain objects?
std::vector<Apple*> vector; // Definitely won't copy the Apple on lookup,
// but I would prefer not to use pointers if I don't have to
std::vector<Apple&> vector; // Seems circuitous?
std::vector<Apple> vector; // I don't know if this copies the Apple on each lookup
My goal is to make it so when I call
Apple& a = vector[4];
the Apple
won't get copied.
I've been using C++ for over a year and I've always worked around this and never understood it. Is there a simple explanation of why one of these three approaches is the best practice?