I heard pointers are not recommended in C++ but I don’t understand why.
My problem is I want to create a vector of class objects to manage my classes.
vector<MyClass> vectorOfClass;
Naturally, for better performance, I should go with a vector of a pointer of class objects?
vector<MyClass *> vectorOfClass;
Or maybe is it possible to create a vector of reference of class objects?
vector<MyClass &> vectorOfClass;
So my questions are :
Or maybe is it possible to create a vector of reference of class objects?
No. Reference are not objects in C++. So you can't create arrays of reference or pointer to references. You can however use a std::reference_wrapper, which wraps reference in an object.
What is the most optimized to create a vector of class objects?
Depends always on the situation. Mesure, profile and make your decision according to your data.
What is the difference between these ways?
They are stored in different ways.
A vector of values look like this in memory:
+----------------------+
| std::vector<MyClass> |----
+----------------------+ |
|
-------------------------
|
v
+-------------+-------------+-------------+-------------+
| MyClass | MyClass | MyClass | MyClass |
+-------------+-------------+-------------+-------------+
Whereas a vector of pointer look like this:
+-----------------------+
| std::vector<MyClass*> |---
+-----------------------+ |
|
------------------
|
v
+-------+-------+-------+-------+
| ptr | ptr | ptr | ptr |
+-------+-------+-------+-------+
| | | |
v | v |
+-------------+ | +-------------+ |
| MyClass | | | MyClass | |
+-------------+ | +-------------+ |
v v
+-------------+ +-------------+
| MyClass | | MyClass |
+-------------+ +-------------+
Both have advantages and disadvantages.
For the value:
For pointer:
std::unique_ptr to own the memory, and most likely allocate every objects distinctly. Allocating a large amount of distinct objects is slow.The default choice should be std::vector<MyClass>. This is by far the simplest and work for most cases. Usually when I need references to those objects, I tend to use index in the vector which are stable as long as there are no element removed in the middle.
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