• Advertisement

Archived

This topic is now archived and is closed to further replies.

Vectors and pointers

This topic is 5062 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

Hey guys, I''m having some trouble with vectors storing pointers to my object. I keep losing data because the objects I create goes out of scope, but the vector doesn''t know this and thus keeps its reference to garbage memory. I have a class that keeps track of messages. class CLogMessage; and I have a manager which has a vector list of those messages. class CLogMgr { std::vector msg_list; } problem is that I add messages from to it and at the end when i want to flush the output to a file, the objects have already been lost and the pointers point to nothing. For now I store the messages as: std::vector msg_list; but the copies are quite expensive because the CLogMessage object contains several strings and such, and this is being called several times per frame. Could someone help me get my vector of pointers working? How do I add an object so that it doesn''t go out of scope?

Share this post


Link to post
Share on other sites
Advertisement
You could try using smart pointers. Both Boost and Loki have good smart pointer implementations. A reference counted smart pointer implementation would help keep the objects alive until every reference is done with them.

Share this post


Link to post
Share on other sites
I''ll look into those. But the thing is I only really have have one reference of each instance. I only mutate it when it gets logged and the rest of the time, the data is only initialized one time.

Basically, the idea was to "Post" a message to the logger. You can do this from anywhere in the app, and later, if you call FlushLog it''ll write unwritten logs to the log files.

The problem is the dynamic objects seem to go out of scope waaay before i flush the data to the files.

I''m thinking I might drop stl for this and go with just a linked list. Seems that trying to use stl is overcomplicating such a simple task.

Share this post


Link to post
Share on other sites
Then you could create the message on the vector in the first place and then manipulate a reference to the object on the vector. That way you don''t do any extra copying.

Or since you only need the one copy, use new to allocate it and then when the log class is done with it, have the log class delete it.

I''m not sure how using your own linked list class would help in these matters.

Share this post


Link to post
Share on other sites

  • Advertisement