std::auto_ptr_ref workings

D

digz

Hi,
The std::auto_ptr 14.4.2 in Stroustrup ,the book talks about
"std::auto_pt_ref is to implement destructive copy semantics" , after
some more search I found that auto_ptr can be returned from function
by value,
and the class auto_ptr_ref is used to achieve that., beyond that the
workings are not mentioned. Can someone help me understand, why is an
auto_ptr_ref needed to return auto_ptr from a function, why is it
different from a normal return statement.

Thx
Digz
 
O

Ondra Holub

digz napsal:
Hi,
The std::auto_ptr 14.4.2 in Stroustrup ,the book talks about
"std::auto_pt_ref is to implement destructive copy semantics" , after
some more search I found that auto_ptr can be returned from function
by value,
and the class auto_ptr_ref is used to achieve that., beyond that the
workings are not mentioned. Can someone help me understand, why is an
auto_ptr_ref needed to return auto_ptr from a function, why is it
different from a normal return statement.

Thx
Digz

Usage example:
class Xyz
{
public:
Xyz()
: data(new int(10))
{
// Here is some other code which may throw an exception
throw SomeException();

// Throwing exception here leads to memory leak -
// data is not cleaned
}

private:
int* data;
};

Version with std::auto_ptr:
class Xyz
{
public:
Xyz()
: data(std::auto_ptr(new int(10)))
{
// Here is some other code which may throw an exception
throw SomeException();

// Throwing exception is safe here -
// data is instance of object, so destructor will
// be called and memory will be correctly freed
}

private:
std::auto_ptr<int> data;
};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top