|
-
October 3rd, 2006, 12:59 PM
#1
Use of auto_ptr
Hi all!
I just read in Meyers, Effective c++ 3rd Edition about resource management. Item 13 describes what I find very interesting, the std::auto_ptr.
I have myself experienced resource leaks due to unexcepted program termination, unexpected thread termination and so on. To avoid these problems auto pointers seems to be just perfect! Is that right?
I guess its not always recommended to use auto_ptr, then my question is when should it be used and when should it not?
It would be tempting to start to use auto_ptr whenever I am using a pointer, but that could not be right.
What I am actually questioning is a little more discussion about when to use this wonderful? auto_ptrs?
Thx
Laitinen
-
October 3rd, 2006, 01:17 PM
#2
Re: Use of auto_ptr
auto_ptr needs to be handled with care. Read Meyers very carefully on the subject. Points to note:
- You cannot use auto_ptrs in an STL container
- Beware of passing auto_ptrs to functions by value
- If you have an auto_ptr member, you will need a user-defined copy constructor and copy assignment operator (or disable them)
- You can't use them to point to an array (i.e. don't use them to hold anything that's been allocated with new[]).
That said, they have their uses, but you may want to explore the various smart pointers offered by boost. Note also that not every pointer in a typical program is suitable for being wrapped in a smart pointer.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
October 3rd, 2006, 02:01 PM
#3
Re: Use of auto_ptr
And, don't forget the ownership semantics of auto_ptr, and the ownership transfer semantics of copy and assignment of auto_ptrs.
There are many pointer scenarii that auto_ptr just don't handle correctly. In that case, you can use other more appropriates smart pointers, such as smart pointers of TR1 or boost. And, sometimes, if none of these smart pointers is appropriate (shared_ptr is quite universally good) you can either program your own smart pointers for your particular scenario, or craft another existing parametrizable smart pointer, or directly use plain old pointers.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
-
October 3rd, 2006, 06:39 PM
#4
Re: Use of auto_ptr
smart pointers are suitable for people that use c++ because of necessity or to look good when they should be using managed c++ or c#. definitely single thread and limited run-time decisions.
Kuphryn
-
October 3rd, 2006, 06:56 PM
#5
Re: Use of auto_ptr
 Originally Posted by kuphryn
smart pointers are suitable for people that use c++ because of necessity or to look good when they should be using managed c++ or c#. definitely single thread and limited run-time decisions.
Kuphryn
It's not to "look good". It's RAII.
We should not be using managed C++ or C#.
smart pointers work find in multi-threaded environments.
I don't know what you could possibly mean by "limited run-time decisions."
Jeff
-
October 4th, 2006, 03:54 AM
#6
Re: Use of auto_ptr
Take a look at the links in the this post.. - http://www.codeguru.com/forum/showpo...1&postcount=12 there's one item by herb sutter as well. You should get the idea - in fact EC++ item should have helped you as well. Take a re-read if you feel necessary. One example application can be this:
Code:
struct One
{
explicit One(int i){//no problem .. cool constructor}
//other members
};
struct Two
{
explicit Two(char c){throw std::runtime_error();} //problematic constructor throws exception
//other members
};
struct A
{
A(int a, char c)
{
std::auto_ptr<One> autoptrToOne(new One(a));
std::auto_ptr<Two> autoptrToTwo(new Two(c));
ptrToOne = autoptrToOne.release(); //can use member get() too
ptrToTwo = autoptrToTwo.release(); //can use member get() too
}
//non-autoptr version
A(int a, char c)
{
ptrToOne = new One(a); //happens successfully
ptrToTwo = new Two(c); //fails - throws exception - what happens to dynamic allocation made for One? memory leak!!!
}
private:
One* ptrToOne;
Two* ptrToTwo;
};
(untested/uncompiled code just for illustration)
Take a look at the above code. See how auto_ptr make it safe to have multiple dynamic allocations safely rolled-back when one of those later ones throws and exception.
Last edited by exterminator; October 4th, 2006 at 07:19 AM.
Reason: had missed the link (added it now)
Can you help me with my homework assignment?, Before you post!, Use code tags, How to post!, Codeguru technical FAQs, C++ FAQ Lite, Stroustrup: C++ Style and Technique FAQ, Guru of the Week, Comeau C and C++ FAQs, Comeau C++ Templates FAQs, CUJ @ DDJ, Spam threshold
My Blogs : Learning C++ is fun | Abnegator's reflections
Open Threads : C++ Aha! Moments | Nature of work in C++?
-
October 4th, 2006, 06:54 AM
#7
Re: Use of auto_ptr
Further to the other comments, I think you should generally only use auto_ptr in three contexts:
1. As a function parameter, where you are explicitly passing ownership of a newed pointer to the function.
2. As the return type of a function, where the function explicitly passes ownership of a newed pointer to the caller. An alternative to this is to pass an auto_ptr by reference as an "out" parameter.
3. To ensure clean up of a pointer via "delete" on exit from a code block.
In general I would not advocate using it in any other context, such as as a member variable of an object, or in a container (which in fact usually won't compile). Other smart pointer classes with different copying semantics are more appropriate or correct in those contexts.
-
October 4th, 2006, 07:21 AM
#8
Re: Use of auto_ptr
In addition to the three main examples given by TomWidmer, as a const non-static data member of a non-copyable class, an auto_ptr makes sense. const auto_ptr have no ownership transfer semantics, since they're non-copyable, non-assignable, and thus, it's just a simple fixed ownership semantic.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
-
October 4th, 2006, 07:56 AM
#9
Re: Use of auto_ptr
Still, in that case, boost::scoped_ptr is slightly less error prone (actually, that's true of my usage 3 as well). Also, it's ok as a non-const member of a non-copyable class too, isn't it? e.g.
Code:
void Foo::setBar(std::auto_ptr<Bar> pBar)
{
m_bar = pBar; //deletes old m_bar, if there was one.
}
-
October 4th, 2006, 11:16 AM
#10
Re: Use of auto_ptr
 Originally Posted by TomWidmer
Also, it's ok as a non-const member of a non-copyable class too, isn't it? e.g.
Yes.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
-
October 4th, 2006, 11:34 AM
#11
Re: Use of auto_ptr
Why can't it be a member of a copyable class??? If you write your copy constructor and assignment operators to create new auto_ptr's, I don't see why there would be a problem? What's the difference between this and copying a class with regular pointers? You just do deep copies!
Code:
#include <memory>
class A
{
public:
A (const long& value) : _p (new long) { *_p = value; }
A (const A& rhs) : _p (new long) { *_p = *(rhs._p); } private:
std::auto_ptr<long> _p; };
int main ()
{
A a1 (10);
A a2 (a1);
return 0; }
-
October 4th, 2006, 11:38 AM
#12
Re: Use of auto_ptr
 Originally Posted by kuphryn
smart pointers are suitable for people that use c++ because of necessity or to look good when they should be using managed c++ or c#. definitely single thread and limited run-time decisions.
Kuphryn
Ehh what?
What are you trying to tell us? It looks like a rant but it might not be and I don't understand the conclusion: "definitely single thread and limited run-time decisions."
No flame, just wondering what is going through your mind.
In response to the OP: as you can see from the number of responses using std::auto_ptr<> might require some thought but IMO learning the semantics of std::auto_ptr<>, boost::shared_ptr<> and boost::weak_ptr<> is time well spent as it will make your code less likely to leak resources and yet doesn't add much typing overhead.
Hope this helps.
PS. Some (not in this thread and not on codeguru) have recommended not using std::auto_ptr<> at all because of the strange "copy" semantics and only use boost::shared_ptr<> and their likes. I wouldn't say that though. Sometimes std::auto_ptr<> is exactly the right tool. One of the reasons is that it's very lightweight in terms of overhead.
Last edited by marten_range; October 4th, 2006 at 11:40 AM.
-
October 4th, 2006, 11:45 AM
#13
Re: Use of auto_ptr
 Originally Posted by sszd
Why can't it be a member of a copyable class??? If you write your copy constructor and assignment operators to create new auto_ptr's, I don't see why there would be a problem?
I didn't said it had any problem. I was only giving a more typical usage (which didn't required any user-defined copy-constructor or destructor).
 Originally Posted by sszd
What's the difference between this and copying a class with regular pointers? You just do deep copies!
Code:
#include <memory>
class A
{
public:
A (const long& value) : _p (new long) { *_p = value; }
A (const A& rhs) : _p (new long) { *_p = *(rhs._p); } private:
std::auto_ptr<long> _p; };
int main ()
{
A a1 (10);
A a2 (a1);
return 0; }
Well, you forgot to overload the copy-assignment operator...
And your example doesn't show a useful usage, though, I know there are real usages of it.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
-
October 4th, 2006, 11:49 AM
#14
Re: Use of auto_ptr
 Originally Posted by sszd
Why can't it be a member of a copyable class??? If you write your copy constructor and assignment operators to create new auto_ptr's, I don't see why there would be a problem? ...
Of course you could be using std::auto_ptr<> in that scenario but IMO it would be better to use a scope guard that has the desired semantics ie in your case some sort of copy_ptr och clone_ptr. It's also less error prone because it won't backfire like std::auto_ptr<> does if you forgot to write your own copy constructor/assigment operator.
Hope this helps
-
October 4th, 2006, 11:52 AM
#15
Re: Use of auto_ptr
 Originally Posted by SuperKoko
Well, you forgot to overload the copy-assignment operator...
And your example doesn't show a useful usage, though, I know there are real usages of it. 
This was only an example of how to copy an auto_ptr, it wasn't meant for anything other than an illustration. I assumed one would be able to extrapolate a copy-assignment operator .
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|