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

Started by
1 comment, last by EddieV223 10 years, 7 months ago

Hello.

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.

Advertisement

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.

Consider using a shared pointer if you are going to need to hold onto the my_class * obj_foo pointer.

If this post or signature was helpful and/or constructive please give rep.

// C++ Video tutorials

http://www.youtube.com/watch?v=Wo60USYV9Ik

// Easy to learn 2D Game Library c++

SFML2.2 Download http://www.sfml-dev.org/download.php

SFML2.2 Tutorials http://www.sfml-dev.org/tutorials/2.2/

// Excellent 2d physics library Box2D

http://box2d.org/about/

// SFML 2 book

http://www.amazon.com/gp/product/1849696845/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1849696845&linkCode=as2&tag=gamer2creator-20

This topic is closed to new replies.

Advertisement