Reputation: 2648
My problem is I'm frontend developer, but I need to add changes to C++ project.
So how it was:
std::vector<myObject*> myArray;
...
myArray.push_back(new myObject);
...
myArray.back();
How I try to change it:
std::vector<std::unique_ptr<myObject>> myArray;
...
myArray.push_back(std::unique_ptr<myObject> (new myObject));
...
myArray.back().get(); // this place looks not good in my opinion :)
A lot of functions should get myObject*
. And I don't know how many changes will be if I change parameters of function.
Could you advise how to get the pointer correctly in this case?
Upvotes: 3
Views: 167
Reputation: 22162
As mentioned in the comments, you should use
myArray.push_back(std::make_unique<myObject>());
(or emplace_back
instead of push_back
) rather than new
. Direct use of new
should be avoided wherever possible.
You shouldn't have to call .get()
on a std::unqiue_ptr
that often.
You can obtain a reference to the stored object with *
:
auto& reference_to_object = *myArray.back();
You can access members directly through ->
:
myArray.back()->some_function();
Only if you need a non-owning pointer (which should be much rarer than a reference) do you need to call .get()
:
auto ptr_to_object = myArray.back().get();
or you can use
auto ptr_to_object = &*myArray.back();
for that (except in the very unlikely case that operator&
is overloaded for myObject
).
I think the issue is that as you say "A lot of functions should get myObject*
". This should be much rarer than you make it sound. Only functions that would also accept a null pointer as argument should take pointers as parameter. Otherwise references should be preferred. The former doesn't happen as frequently.
Also note that you really should have a good reason to use (smart) pointers at all inside the std::vector
. There are few reasons not to just use std::vector<myObject>
, such as myObject
not being movable, being very expensive to move, myObject
being used polymorphically or references to the contained objects being required to not be invalidated when elements are added/removed. (Although std::list
might work better in the latter case.) If none of these, or other reasons I forgot to mention, apply, just use std::vector<myObject>
.
Upvotes: 10