Thread: How do you collect garbage from a vector of a class pointer?

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    100

    How do you collect garbage from a vector of a class pointer?

    Hello. How do you collect garbage from a vector of a class pointer (let's say, MyClass*)? Since I'm just barely starting out with STL, a really simple and easy to follow solution would be most appreciated. I'm guessing you can just go through it with an iterator and keep calling delete on the dereferenced iterator, but that doesn't sound like a very good way to do it. Thanks!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Yes, that is a way to do it. If you don't actually need to store pointers in the vector, a simpler solution is to use a vector<MyClass>. If you must store pointers, a more robust solution is to use vector<shared_ptr<MyClass>> (or vector<unique_ptr<MyClass>>, depending on your needs), but std::shared_ptr and std::unique_ptr are new additions to the C++ standard library and so might not be available.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    100
    Thanks much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Collect multiple lines of inputs
    By drag0n69 in forum C Programming
    Replies: 10
    Last Post: 02-25-2008, 12:45 AM
  2. Replies: 2
    Last Post: 09-09-2007, 12:58 AM
  3. Making stack class using vector class
    By spank in forum C++ Programming
    Replies: 9
    Last Post: 08-10-2007, 03:50 AM
  4. finding derived class type of a pointer to a base class
    By LinuxCoder in forum C++ Programming
    Replies: 15
    Last Post: 04-10-2006, 11:08 AM
  5. Collect Coins & Score System
    By Mecnels in forum Game Programming
    Replies: 4
    Last Post: 12-07-2004, 01:42 PM