473,785 Members | 2,607 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 3055
gr**********@pa cbell.net wrote:
On Mon, 20 Oct 2003 01:32:05 +0100, lilburne <li******@godzi lla.net> wrote:
gr**********@pa cbell.net wrote:

You can get away with the reference if you know where the data is
going to end up, but say for example that calculate_some_ geometry() is
destructive and may fail, you'll want to do the calculation and only
if it is OK replace the original data. Taking over a pointer avoids a
final copy.


I am not getting it. Either your calculate_some_ geometry() may fail or not.
If it fails you need a copy , if it doesn't you don't.


Not if you have a pointer. You just replace the pointer no
extra copy required.

Jul 19 '05 #31
Rob Williscroft wrote:
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<Point3 D> 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:


The amount of data that std::vector may hold can be very
large, you really don't want to be copying it. Example
500,000 points is quite typical in CADCAM applications, you
do not want to be copying that amount of data about, if you
can possibly help it.

Also each time std:vector has to resize, the current data
gets copied, you have to have enough contigous memory to
hold the new size, and in the worst case half the space is
unused. Also as the internal buffer grows you are likely to
end up with a fragmented memory map.

Jul 19 '05 #32
lilburne wrote in news:bn******** ****@ID-203936.news.uni-berlin.de:
Rob Williscroft wrote:
lilburne wrote in news:bm******** ****@ID-203936.news.uni-berlin.de:

[snip]

Returning large objects on the stack is a worse idea.

[snip]

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:


The amount of data that std::vector may hold can be very
large, you really don't want to be copying it. Example
500,000 points is quite typical in CADCAM applications, you
do not want to be copying that amount of data about, if you
can possibly help it.


None of that makes std::vector<> a "large object on the stack".

Also with (N)RVO, return by value and construction completely
by-passes the copy constructor, so it is a sutible way to
create a std::vector<>, no matter how many points it has.
This may not suit the way you code, but that doesn't make
all return by value (even of "large" objects) a bad idea.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #33
Rob Williscroft wrote:
lilburne wrote in news:bn******** ****@ID-203936.news.uni-berlin.de:

The amount of data that std::vector may hold can be very
large, you really don't want to be copying it. Example
500,000 points is quite typical in CADCAM applications, you
do not want to be copying that amount of data about, if you
can possibly help it.

None of that makes std::vector<> a "large object on the stack".

Also with (N)RVO, return by value and construction completely
by-passes the copy constructor, so it is a sutible way to
create a std::vector<>, no matter how many points it has.


Avoiding a default constructor by return value optimization
is of minimal use when the underlaying result is the copying
of a Mb of data. If one stuffs 100,000 3D points into a
vector the data it holds is over 2Mb. When the vector is
returned, whether or not 12 bytes are physically transferred
on the stack or not, ultimately over 2Mb of data is copied
into the receiving object, not just 12 bytes.

Jul 19 '05 #34
lilburne wrote in news:bn******** ****@ID-203936.news.uni-berlin.de:

Avoiding a default constructor by return value optimization
That isn't what RVO does.
is of minimal use when the underlaying result is the copying
of a Mb of data. If one stuffs 100,000 3D points into a
vector the data it holds is over 2Mb. When the vector is
returned, whether or not 12 bytes are physically transferred
on the stack or not, ultimately over 2Mb of data is copied
into the receiving object, not just 12 bytes.


Not in this case:

std::vector< int > create()
{
std::vector< int > nrv;
// populate ...
return nrv;
}

int main()
{
std::vector< int > res( create() );
}

Assuming you have a compiler that support NRVO, there is NO
copying of a std::vector< int >.

How it can work the address of the yet-to-be-constructed res is
passed as a hidden argument to create(), create() constructs res
(it's local nrv is an alias for main's res) populates res/nrv
and return's. No copying.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #35
gr**********@pa cbell.net wrote in message news:<op******* *******@news.sf .sbcglobal.net> ...
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.


To rephrase the OP's question, "Why would you ever want to use auto_ptr
when you could just create an automatic variable and return it by value?"
There are several possible answers:

1. The class might be expensive to copy.
2. The class might not be copyable at all.
3. The class might be designed so that it can only be
created on the heap (e.g., using a factory).
4. The class might be used polymorphically .

Note that the NRVA might compensate for #1, but since it is an optimisation
you can't count on it. In any case, it won't compensate for #2 since a copy
constructor must still be accessible even if it is elided.
auto_ptr holds a single object, the code that uses it does not really use
polymorphizm - because the object is single.
This doesn't follow. There are many cases where a single object is
used polymorphically . For example, consider any function that takes a
basic_ostream parameter.
Template is better solution then auto_ptr, also much faster.


It seems to me that they solve different problems.
Jul 19 '05 #36
Rob Williscroft wrote:
lilburne wrote in news:bn******** ****@ID-203936.news.uni-berlin.de:

Avoiding a default constructor by return value optimization


Assuming you have a compiler that support NRVO, there is NO
copying of a std::vector< int >.


That is one big assumption. Besides code that relies on a
compiler optimization is a wee bit suspect. Supposing the
NVRO compiler decides not to optimize? Since 1992 I've seen
the g++ compiler optimize the same code differently in each
version, and mostly it has become more cautious in its
optimizations as bugs have been discovered.

Jul 19 '05 #37
lilburne wrote in news:bn******** ****@ID-203936.news.uni-berlin.de:
Rob Williscroft wrote:
lilburne wrote in news:bn******** ****@ID-203936.news.uni-berlin.de:

Avoiding a default constructor by return value optimization


Assuming you have a compiler that support NRVO, there is NO
copying of a std::vector< int >.


That is one big assumption. Besides code that relies on a
compiler optimization is a wee bit suspect. Supposing the
NVRO compiler decides not to optimize?


The assumption above was on my part. There is no assumtion on your
part you either have a compiler that suports NVRO or you don't. If
you don't get a compiler that does.

NVRO is the common name for a set of language features, technicaly not
an optimisation as it's allowed to break the as-if rule. It is nothing
to do with a compilers optimizer and a supporting compiler will do it
with all optimizations turned off. Though maybe it would have a switch
to turn it off (like many compilers have for RTTI etc) but I can't think
why it would.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #38
Rob Williscroft wrote:
lilburne wrote in news:bn******** ****@ID-203936.news.uni-berlin.de:

Rob Williscroft wrote:

Assuming you have a compiler that support NRVO, there is NO
copying of a std::vector< int >.


That is one big assumption. Besides code that relies on a
compiler optimization is a wee bit suspect. Supposing the
NVRO compiler decides not to optimize?

The assumption above was on my part. There is no assumtion on your
part you either have a compiler that suports NVRO or you don't. If
you don't get a compiler that does.

NVRO is the common name for a set of language features, technicaly not
an optimisation as it's allowed to break the as-if rule. It is nothing
to do with a compilers optimizer and a supporting compiler will do it
with all optimizations turned off. Though maybe it would have a switch
to turn it off (like many compilers have for RTTI etc) but I can't think
why it would.


Well I thought "maybe he isn't clueless", and decided to put
it to the test. I tried gcc 3.3.1 which is supposed to have
NVRO and you know what ... it copies the data.
Jul 19 '05 #39
lilburne escribió:
Well I thought "maybe he isn't clueless", and decided to put
it to the test. I tried gcc 3.3.1 which is supposed to have
NVRO and you know what ... it copies the data.


I make this little test with 3.3 20030226

#include <iostream>

using std::cout;
using std::endl;

class A
{
public:
A ()
{
cout << "Constructo r" << endl;
}
A (const A &)
{
cout << "Copy constructor" << endl;
}
};

A f ()
{
return A ();
}

int main ()
{
cout << "a" << endl;
A a = f ();
cout << "b" << endl;
A b= a;
}

The output is:

a
Constructor
b
Copy constructor

No copy construction for a, and the copy constructor clearly works.

How do you tested in gcc 3.3.1?

Regards.
Jul 19 '05 #40

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
3551
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
3498
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
1587
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
10074
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
9645
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
10155
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
10095
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
9954
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...
1
7502
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
6741
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
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.