473,770 Members | 1,642 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I cannot see the need for auto_ptr?!

Hello,

I realise that I just dont get this, but I cannot see the need for auto_ptr.
As far as I have read, it means that if you create an object using an
auto_ptr, instead of a raw pointer, then the object will get cleaned up when
the method/function ends. Isn't this what happens if you just declare an
object without using a pointer at all? Aren't these examples the same (I
know they will not be, but I am hoping someone may explain to me what I am
missing here!):

void f()
{
T t;
t.SomeFunc();
} // cleanup when function ends

void f()
{
auto_ptr<T> pt(new T);
pt->SomeFunc();
} // cleanup when function ends

Wish I could see what is going on here!

Jamie.
Jul 19 '05
45 3053
On Mon, 20 Oct 2003 04:03:09 GMT, gr**********@pa cbell.net wrote:

Yes, but returning a pointer from foo is a bad progamming practice.
Why don't you just say that auto_ptr is deprecated ?


Each of your sentences parse as english, but neither is meaningful
to me (as far as I know it's never been regarded as bad practice to
return pointers from functions, and as far as I know std::auto_ptr is
not deprecated and has not been suggested for deprecation), and
furthermore, to me they seem mutually contradictory.

What is it you're trying to say?

Jul 19 '05 #21


gr**********@pa cbell.net wrote:

void bar()
{
std::auto_ptr<L argeObject> p = foo();

p->doTheFandango( );
}

where the call to 'foo' transfers ownership up to the local
std::auto_ptr in 'bar', which guarantees deallocation even if, as Murphy
guarantees will happen, 'doTheFandango' throws an exception.
Yes, but returning a pointer from foo is a bad progamming practice.


Says who?
Sometimes you don't have a choice.
Why don't you just say that auto_ptr is deprecated ?


You are concentrating too much on returning pointers.

void bar( int Type )
{
Obj* pObj;

pObj = Factory.CreateO bject( Type );

// do something

// object no longer needed, delete it.

delete pObj;
}

Now lets say, that the part // do something is rather complicated and there
is a chance that things might go wrong. You insert some tests and do a return.
But when doing so you must not forget do delete the object given to you
from the factory.
void bar( int Type )
{
Obj* pObj;

pObj = Factory.CreateO bject( Type );

// do something
...
if( SomeTest ) {
delete pObj;
return;
}

if( SomeOtherTest ) {
...
while( ... ) {
if( AThirdTest )
return;
}
}
// object no longer needed, delete it.

delete pObj;
}

So you see the big? Deep inside the while, there is an if which returns. It happened
to me, that I forgot to delete pObj, because I am human :-)

An auto_ptr saves me from all of this. I don't need to remember to delete pObj, it
is done automatically for me. For the very same reason that you use vector instead
of dynamically allocated arrays, you use an auto_ptr when you must use a pointer, to
free yourself from human errors and to easen maintenance (who says that this test
was there in the first place. It could have been added weeks later).

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 19 '05 #22


gr**********@pa cbell.net wrote:

On Mon, 20 Oct 2003 02:11:56 GMT, Howard Hinnant <hi*****@metrow erks.com>
wrote:
So the X(T*) constructor first establishes ownership of the passed in ptr
with an auto_ptr. This is a no-throw operation, guaranteed to succeed.
Now the constructor goes about its other business. If anything following
throws an exception, the local auto_ptr destructor insures that the T* is
properly cleaned up. After construction is complete, the X officially
takes ownership of the T* by transferring it from the auto_ptr.


And that's exactly the problem.

-Howard


Why dynamic allocations in exceptions sensitive code ?


Every code is exception sensitive, except when written explicitly otherwise.
auto_ptr *is* a tool for taking care of exceptions.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 19 '05 #23
lilburne wrote in news:bm******** ****@ID-203936.news.uni-berlin.de:

[snip]

Returning large objects on the stack is a worse idea.

// performance killer
vector<Point3D> calculate_some_ geometry()
{

vector<Point3D> geometry;

// do something that adds lots of points to geometry

return geometry;
}


std::vector< T > is not a large object typicaly its the size of
3 pointers (12 bytes on my machine). The T's that it containes
are held in storage provided by std::allocator< T > which in turn
get its storage from operator new(), which allocates memory from
free storage aka the heap.

Note also the above example should benefit from NRVO so it should
perform as well as ( and some times better than ) this:

void calculate_some_ geometry( vector<Point3D> &geometry )
{
// do something that adds lots of points to geometry
}

The situation in wich it can perform better is:

vector<Point3D> geometry( calculate_some_ geometry() );

There is no array version of std::auto_ptr<> , but then we have
std::vector<> so we don't need it :).

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #24
On Mon, 20 Oct 2003 04:15:23 GMT, Alf P. Steinbach <al***@start.no > wrote:
On Mon, 20 Oct 2003 04:03:09 GMT, gr**********@pa cbell.net wrote:

Yes, but returning a pointer from foo is a bad progamming practice.
Why don't you just say that auto_ptr is deprecated ?


Each of your sentences parse as english, but neither is meaningful
to me (as far as I know it's never been regarded as bad practice to
return pointers from functions, and as far as I know std::auto_ptr is
not deprecated and has not been suggested for deprecation), and
furthermore, to me they seem mutually contradictory.

What is it you're trying to say?


Hi,
A little bit more to parse. Look at the original post. Instead of dynamic
allocation of a single object hold by an auto_ptr we could always use an
automatic variable, maybe inside a template.
auto_ptr holds a single object, the code that uses it does not really use
polymorphizm - because the object is single.
Template is better solution then auto_ptr, also much faster.
--
grzegorz
Jul 19 '05 #25
On Mon, 20 Oct 2003 11:25:12 GMT, gr**********@pa cbell.net wrote:
Yes, but returning a pointer from foo is a bad progamming practice.
Why don't you just say that auto_ptr is deprecated ?
Each of your sentences parse as english, but neither is meaningful
to me (as far as I know it's never been regarded as bad practice to
return pointers from functions, and as far as I know std::auto_ptr is
not deprecated and has not been suggested for deprecation), and
furthermore, to me they seem mutually contradictory.

What is it you're trying to say?
A little bit more to parse. Look at the original post. Instead of dynamic
allocation of a single object hold by an auto_ptr we could always use an
automatic variable, maybe inside a template.
auto_ptr holds a single object, the code that uses it does not really use
polymorphizm - because the object is single.
Template is better solution then auto_ptr, also much faster.


This makes even less sense! A template to hold an automatic variable?
auto_ptr does not use polymorphism? What? What?

Are you seriously saying that you can't think of a SINGLE time when you
might want to use auto_ptr or a similar smart pointer class?

--
Be seeing you.
Jul 19 '05 #26
On Mon, 20 Oct 2003 10:12:22 +0200, Karl Heinz Buchegger
<kb******@gasca d.at> wrote:


gr**********@pa cbell.net wrote:

Why dynamic allocations in exceptions sensitive code ?


Every code is exception sensitive, except when written explicitly
otherwise.
auto_ptr *is* a tool for taking care of exceptions.


Yes, but the code doesn't neccesery have to use dynamic allocation.
--
grzegorz
Jul 19 '05 #27
On Sun, 19 Oct 2003 21:40:55 +0100, "Jamie Burns" <se*****@email. com>
wrote:
Hello,

I realise that I just dont get this, but I cannot see the need for auto_ptr.
As far as I have read, it means that if you create an object using an
auto_ptr, instead of a raw pointer, then the object will get cleaned up when
the method/function ends. Isn't this what happens if you just declare an
object without using a pointer at all? Aren't these examples the same (I
know they will not be, but I am hoping someone may explain to me what I am
missing here!):

void f()
{
T t;
t.SomeFunc();
} // cleanup when function ends

void f()
{
auto_ptr<T> pt(new T);
pt->SomeFunc();
} // cleanup when function ends

Wish I could see what is going on here!


Use auto_ptr when you want to transfer ownership of pointers around in
an exception safe way. e.g.

struct Foo
{
void transferBase(Ba se* subelement);
//...
};

vs.

struct Foo
{
void transferBase(au to_ptr<Base> subelement);
//...
};

The second version enforces the transferral of ownership in an
exception safe manner.

Tom
Jul 19 '05 #28
On Mon, 20 Oct 2003 11:42:06 GMT, gr**********@pa cbell.net wrote:
On Mon, 20 Oct 2003 10:12:22 +0200, Karl Heinz Buchegger
<kb******@gasc ad.at> wrote:


gr**********@pa cbell.net wrote:

Why dynamic allocations in exceptions sensitive code ?


Every code is exception sensitive, except when written explicitly
otherwise.
auto_ptr *is* a tool for taking care of exceptions.


Yes, but the code doesn't neccesery have to use dynamic allocation.


Often it does (e.g. polymorphism or non-copyable objects).

Tom
Jul 19 '05 #29


gr**********@pa cbell.net wrote:

On Mon, 20 Oct 2003 10:12:22 +0200, Karl Heinz Buchegger
<kb******@gasca d.at> wrote:


gr**********@pa cbell.net wrote:

Why dynamic allocations in exceptions sensitive code ?


Every code is exception sensitive, except when written explicitly
otherwise.
auto_ptr *is* a tool for taking care of exceptions.


Yes, but the code doesn't neccesery have to use dynamic allocation.


True.
But in case it has to, auto_ptr is there to help.

I am with you that dynamic allocations should be kept to
a minimum. But in real world programs it is often necessary
to have them and to deal with pointers. Eg. object factories
wouldn't be possible without them in C++.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 19 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1118
by: Jason Heyes | last post by:
My main program #include <iostream> #include <algorithm> #include <iterator> #include <vector> #include "M.h" using namespace std; int main()
5
4082
by: gg | last post by:
I am getting the following compilation errors with the following program. My compiler is aCC 03.27 on HP-UX11 - #include <iostream> using namespace std; #include <list> #include <memory> #include <string>
4
3550
by: Rein Anders Apeland | last post by:
Consider the following working code: #include <memory> #include <iostream> void print_ptr( const std::auto_ptr< int > & thePtr = std::auto_ptr< int >() ) {
14
3497
by: Andrew | last post by:
Hello all: After spending some time figuring out auto_ptr class' implementation, I decided to write a small article detailing its use of the auto_ptr_ref proxy class to enable construction and assignment from temporaries. I have placed the manuscript at: http://www.nd.edu/~ahenrick/auto_ptr.pdf It develops the problem and its solution in an incremental manner, which will hopefully make it accessible for most people without being
9
2921
by: dragoncoder | last post by:
Hi all, I am trying to understand the auto_ptr_ref role in the implementation of auto_ptr<>. I read the information on net but still not 100% sure of it. My plan is as follows. 1. To see the behaviour of std::auto_ptr. 2. To implement a pkt::auto_ptr without auto_ptr_ref. 3. Check out the limitations of pkt::auto_ptr as compared to std::auto_ptr (using steps 1 and 2).
14
1586
by: Pep | last post by:
I have a method in a class like this class myClass { ... ctros, dtor, etc ... string myClassMethod() { string myString = "";
39
864
by: Andre Siqueira | last post by:
Hello all, I have a member function like thist: Query(const std::string & id, std::auto_ptr<Modifiermodif = std::auto_ptr<Modifier>()) when a try to instantiate a Query like Query("123");
10
3825
by: mosfet | last post by:
Hi, Let's say I have a vector of auto_ptr defined like this : vector< auto_ptr<T v; is it allowed ? Is there any side effects ? If it's not a good idea, how can I fix this ?
17
10073
by: Ankur Arora | last post by:
Hi All, I'm building a sample application that uses a custom auto_ptr implementation. The program crashes with the following output:- Output (Debug Assertion failed) ----------
0
9595
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10232
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10059
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10008
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9873
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8891
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7420
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6682
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.