Wednesday, April 16, 2008

Quick std::vector question - GameDev.Net Discussion Forums

Quick std::vector question - GameDev.Net Discussion Forums: "This is a good place to tell you to learn about smart pointers. They are objects that act like pointers, and logically 'own' the object, and are responsible for cleaning them up automatically. std::auto_ptr's are part of the standard library, but you can't use these in any of the standard containers. For a nice smart pointer (they are reference-counted smart pointers), learn about the boost.shared_ptr library."


#include
#include
#include

class bar
{
public:
bar() {std::cout << "bar constructor called" << std::endl;}
~bar() {std::cout << "bar destructor called" << std::endl;}
};


class foo
{
boost::shared_ptr i;

public:
foo();
void doSomethingWithTheBar();
};


foo::foo() : i(new bar)
{
std::cout << "newing a bar" << std::endl;
std::cout << "bar's address: " << i << std::endl;

}

void foo::doSomethingWithTheBar()
{
std::cout << "Do something with bar at address: " << i << std::endl;
}


int main()
{
std::vector vec;
{
foo f;
vec.push_back(f);
}
vec[0].doSomethingWithTheBar();
std::cout << "It's ok this time, as the memory at that address hasn't been deleted" << std::endl;
}


No comments:

Post a Comment