Jump to content
  • Advertisement
Sign in to follow this  

SOLVED c++ keeping a pointer or reference to a object stored in vector<unique_ptr<my_object>> possible is it posible? and how?

This topic is 2107 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


I am aware that adding and removing objects from vector will at some point cause it to "resize" and therefore replace its position in memory in some cases.

I have a vector that stores unique_ptr of my object and there are gonna be ranging from 1-? , and they are only defied at runtime and are resized during runtime.

as so:

std::vector<std::unique_ptr<my_class>> list;

What i need is to make a pointer or reference to first object somewhere else in the code.

I am afraid that setting it simply like this:

my_class * obj_foo;
obj_foo = list[0].get();

is not bullet proof.


Question: Will the "obj_foo" to go corrupt at some point, and not point to the first object in the vector(since vector will move it self to place where it has enough memory place).

Or am i wrong?  is that the case?


NOTE: I tested it, and it seamed to keep the pointer intact but dosen't hurt to ask.

Share this post

Link to post
Share on other sites

The pointer obj_foo is not pointing to the first object in the vector. It is pointing to the same thing that the first smart pointer object in the vector points to. So the smart pointer can relocate, but it will still point to the same thing if the vector triggers a reallocation.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!