Quick question:
Is saying
#include <vector>
vector<Object*>* arr = new vector<Object*>();
a parallel-version/similar/etc to
Object** arr = new Object*[100]; //I guess any size can do since vector maximum size changes all the time.
?
And if I am wrong could someone correct me?
I think what you need is:
vector<Object*> arr;
This will be an "array" of pointers. (the array will be automatically destroyed when you leave the scope that you declare it in).
Of course, you can have vector<Object*>*
, but it is more similar to
Object*** arr = new Object**;
*arr = new Object*[100];
There's more similarity between this
#include <vector>
vector<Object*> arr(100);
and this
Object** arr = new Object*[100];
Why do people feel the need to new everything all the time? I think because its complicated and therefore it must be good, right? Wrong actually.
Really, the "parallelism" that you're looking for is between the following two definitions:
vector<Object*> arr;
Object** arr = new Object*[100];
The only way in which these are "parallel versions" of each other is that they both provide some sort of set or list of pointers to Object
. They are both, in a sense, "arrays" of pointers to Object
and you could access a member x
of the objects like arr[0]->x
with both. However, neither is truly of type array of pointer to Object
.
In particular, the thing that makes your first definition different to the second is that you have a pointer to the vector
. In that case you would access member x
like (*arr)[0]->x
, having to dereference the pointer first.
These two definitions of arr
are very different to each other in many ways though, so I would never think of them as being similar. The first is more idiomatic C++ because the vector will sort out the allocation and deallocation of the pointers for you. With the second, you'll need to remember to call delete[]
later on. The vector
also gives you a dynamically sized container and many of the other awesome features that come as part of a vector
.
However, neither is the best choice as far as writing clean and idiomatic C++ is concerned. Regardless of which choice you make, you're still going to have to allocate (with new
) the actual Object
s that you're going to store pointers to and then remember to delete
them. Your best choice here is to just use a vector<Object> arr
. If, for some reason, you really need to store pointers to the objects, then you're much better off using some kind of smart pointer, such as in vector<shared_ptr<Object>> arr
. If your container is going to be of fixed size (like the array of size 100 in your example), then you might prefer to use array<Object, 100>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.