• Advertisement
Sign in to follow this  

std::auto_ptr()

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

I have been reading the book Effective C++, and came across auto_ptr(). I really like the idea of having it manage the deletion of objects. How many of you use auto_ptr() or shared_ptr() in your programs? I always enjoy discovering something new in the C++ language. For those of you that never used this before here is simple program I wrote to demonstrate it.
//==================================================
//main.cpp
//Program tests the use of auto_ptr
//==================================================
#include <iostream>
#include <memory>

using namespace std;

class TestClass
{
public:
	TestClass(){cout<<"Entering Constructor"<<endl;}
	~TestClass(){cout<<"Entering Destructor"<<endl;}
	void setA(int a){m_a = a;}
	void setB(int b){m_b = b;}
	int getA(){return m_a;}
	int getB(){return m_b;}

private:
	int m_a;
	int m_b;

};

int main()
{
	cout<<"Creating TestClassObject"<<endl;
	auto_ptr<TestClass>pClass(new TestClass());
	pClass->setA(5);
	pClass->setB(17);
	cout<<"Value of a is "<<pClass->getA()<<endl;
	cout<<"Value of b is "<<pClass->getB()<<endl;
	cout<<"Not calling delete on pClass"<<endl;


	return 0;
}

Share this post


Link to post
Share on other sites
Advertisement
I do use it occasionally, but usually I'll use shared_ptr instead. Just make sure that you don't use it to store a pointer to an array.

Share this post


Link to post
Share on other sites
I haven't found it as useful as I would expect it to be. However, it's a particularly good idea for use with factory functions:


class Base {
static auto_ptr<Base> create(const vector<string>& args) {
// depending on args, return some Derived
}

virtual void doSomething() = 0;
};

class Derived1 : public Base {
// implement doSomething()
};
class Derived2 : public Base {
// implement doSomething()
};

int main(int argc, char** argv) {
Base::create(vector<string>(argv, argv + argc))->doSomething();
// polymorphism AND automatic memory management? Oh my!
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement