Vectors and pointers

Started by
2 comments, last by VI2 20 years ago
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?
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.
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.
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.

This topic is closed to new replies.

Advertisement