473,624 Members | 2,104 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

When to use 'new' and when not

Hi,

say I have a class X, such that:

class X
{
A a;
B b;
C c;
...
K k;
};

with each object a-k being of quite some size (that means, it's way
larger than just a pointer or maybe even a string).
Now X is istantiated in the program entry point, that is, it resides on
the stack of main().

How large can x be to not lead to a stack overflow? Is it (in those
cases) generally a better idea to just let X hold pointers and allocate
memory dynamically?

In my applications, I almost never use dynamic memory allocated by
'new'. Are there any guidelines when to do that, and when not?

--
Matthias Kaeppler
Jul 23 '05 #1
5 1641
Matthias Kaeppler wrote:
Hi,

say I have a class X, such that:

class X
{
A a;
B b;
C c;
...
K k;
};

with each object a-k being of quite some size (that means, it's way
larger than just a pointer or maybe even a string).
Now X is istantiated in the program entry point, that is, it resides on
the stack of main().

How large can x be to not lead to a stack overflow?

That's system dependant. Actually, it's even system dependant whether there
is a stack (in the sense you're using the word) at all. Also, the amount of
usable stack space depends on lots of other things, and it typically is
possible to specify the stack size at compile time with a compiler command
line option.
Is it (in those cases) generally a better idea to just let X hold pointers
and allocate memory dynamically?
I'd allocate dynamically only if I really need to. If your object really
happens to be too big (like - say - half a megabyte), you can still
allocate the X object dynamically and keep the members as they are.
In my applications, I almost never use dynamic memory allocated by
'new'. Are there any guidelines when to do that, and when not?


dynamically allocated objects are often needed if the size is not known at
compile time (e.g. like std::string, which doesn't know how many characters
there will be), or when using polymorphic types, when you don't know at
compile-time which type to instantiate. Another use is if you want to avoid
copying the object. You can allocate it dynamically and copy only the
pointer.
Jul 23 '05 #2

"Matthias Kaeppler" <no****@digital raid.com> wrote in message
news:d3******** *****@news.t-online.com...
Hi,

say I have a class X, such that:

class X
{
A a;
B b;
C c;
...
K k;
};

with each object a-k being of quite some size (that means, it's way
larger than just a pointer or maybe even a string).
Now X is istantiated in the program entry point, that is, it resides on
the stack of main().

How large can x be to not lead to a stack overflow?
That depends on the system's or application's stack size.
Is it (in those
cases) generally a better idea to just let X hold pointers and allocate
memory dynamically?
That depends on whether you want to run the risk of running out of stack
space. If the objects are huge, I'd say yes, allocate them dynamically.
In my applications, I almost never use dynamic memory allocated by
'new'.
And you've never run into stack overflow problems?
Are there any guidelines when to do that, and when not?


Why do you like stack-based objects so much? Is it because you don't like
having to worry about deleting them? If so, then you could use auto_ptr,
which is a stack-based object that holds a pointer to a dynamically
allocated object. Thus, auto_ptr offers best of both worlds.

For example:

#include <memory>
int main( void )
{
// 'x' will be destroyed automatically when exitting the current scope
std::auto_ptr<X > x( new X );

return 0;
}

You can even use auto_ptr's for class members:

#include <memory>
class X
{
std::auto_ptr<A > a;

public:
X();
};

X::X()
// 'a' will be destroyed automatically when this instance of X is
destroyed
: a( new A )
{
}

- Dennis
Jul 23 '05 #3
Dennis Jones wrote:
How large can x be to not lead to a stack overflow?

That depends on the system's or application's stack size.


And how can I figure that out to get a clue?
Is it (in those
cases) generally a better idea to just let X hold pointers and allocate
memory dynamically?

That depends on whether you want to run the risk of running out of stack
space. If the objects are huge, I'd say yes, allocate them dynamically.


What does huge mean, 1MB, 10MB, 100MB?
In my applications, I almost never use dynamic memory allocated by
'new'.

And you've never run into stack overflow problems?


No.
Are there any guidelines when to do that, and when not?

Why do you like stack-based objects so much? Is it because you don't like
having to worry about deleting them? If so, then you could use auto_ptr,
which is a stack-based object that holds a pointer to a dynamically
allocated object. Thus, auto_ptr offers best of both worlds.


I don't like them any better than an object which memory was allocated
dynamically. However, calls to new and delete produce additional code,
and if I'm not 100% certain that I need dynamic allocation, why pay for it?
I'm very aware of smart pointers by the way, the reason I ask is more
due to the fact that I never had any problems with stack overflows or
such, so I never saw a reason in using new and delete much.
However, I agree this is kind of short-sighted :)

--
Matthias Kaeppler
Jul 23 '05 #4
Matthias Kaeppler wrote:
Say that I have a class X, such that:

class X {
A a;
B b;
C c;
...
K k;
};

with each object a-k being of quite some size (that means that
it's way larger than just a pointer or maybe even a string).
Now X is istantiated in the program entry point,
that is, it resides on the stack of main().
I think that most comp.lang.c++ subscribers would prefer that
you use the term *automatic storage* instead of stack
even though the typical implementation
(and, in fact, every ANSI/ISO C++ compliant implementation)
allocates automatic storage from the program stack.
How large can x be to not lead to a stack overflow?


For the typical implementation, you can think of [virtual] memory
as a sequence of addresses:

top
--------
00000000
00000001
00000002
Jul 23 '05 #5
E. Robert Tisdale wrote:
Matthias Kaeppler wrote:
Say that I have a class X, such that:

class X {
A a;
B b;
C c;
...
K k;
};

with each object a-k being of quite some size (that means that
it's way larger than just a pointer or maybe even a string).
Now X is istantiated in the program entry point,
that is, it resides on the stack of main().

I think that most comp.lang.c++ subscribers would prefer that
you use the term *automatic storage* instead of stack
even though the typical implementation
(and, in fact, every ANSI/ISO C++ compliant implementation)
allocates automatic storage from the program stack.
How large can x be to not lead to a stack overflow?

For the typical implementation, you can think of [virtual] memory
as a sequence of addresses:

top
--------
00000000
00000001
00000002
.
.
.
FFFFFFFE
FFFFFFFF
--------
bottom

The program stack grows upward [into free storage] from the bottom
of [virtual] memory and "dynamic memory" is allocated starting
somewhere near the top of [virtual] memory
(usually just after the .text [code] and .data [static data] segments)
and grows downward into free storage.
You run out of stack space only when you run out of free storage.
Stack overflow is almost always the result of exceeding
some artificial limit on the stack size set by your operating system
or by your program. For example, on my Linux workstation:
> limit stacksize

stacksize 10240 kbytes

which I can easily reset:
> limit stacksize unlimited
> limit stacksize

stacksize unlimited

This limit serves as a check on runaway processes
such as a call to a recursive function which never returns.
Is it (in those cases) generally a better idea
to just let X hold pointers and allocate memory dynamically?

In my applications,
I almost never use dynamic memory allocated by 'new'.
Are there any guidelines when to do that, and when not?

Usually, dynamic memory allocation should be reserved
for objects such as arrays
for which the size is not known until runtime.

Most objects allocated from automatic storage are small
but reference much larger objects through pointers
into dynamically allocated memory (using new in their constructors).

Usually, the compiler emits code to allocate automatic storage
for all of the local objects including large arrays
upon entry into the function.
Right now, it appears that
C++ will adopt C99 style variable size arrays
which will complicate the situation a little.
Now, to answer your question,
you should generally avoid new
unless the object must survive the scope where it was created.
For example:

class doubleVector {
private:
double* P;
size_t N;
public:
doubleVector(si ze_t n): P(new double[n]), N(n) { }
~doubleVector(v oid) { delete [] P; }
};

When you create a doubleVector:

doubleVector v(n);

automatic storage is allocated for v.P and v.N [on the program stack]
but the array itself is allocated from free storage by the constructor
using new.
The destructor is called and frees this storage
when the thread of execution passes out of the scope
where v was declared.

Is it wise to allocate very large objects from automatic storage?
Probably not. It will probably interfere with other stack operations
by causing an extra page fault even before you access the object.
But, because it depends upon the implementation,
there is very little general guidance that we can give you.
The distinction between large and small objects
depends upon how much memory you have -- 256MByte? 2GByte? More?
Many new platforms have enough physical memory
to store *all* of virtual memory!

The best advice that we can give you is to test both
automatic and dynamic storage for large objects
and use automatic storage if you don't find an appreciable difference.


That was an insightful read, thanks Robert.

--
Matthias Kaeppler
Jul 23 '05 #6

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

Similar topics

1
7966
by: Vetrivel | last post by:
Application architecture : Develop interface between two existing systems, a. Enterprise CRM system b. Web based intranet system. Environment : Intranet Server : IIS and ASP. Script : VBScript and Javascript Client : 1. IE browser. 2. VBForm embedded with WebBrowser control (MS Internet
1
4018
by: Rhy Mednick | last post by:
I'm creating a custom control (inherited from UserControl) that is displayed by other controls on the form. I would like for the control to disappear when the user clicks outside my control the same way a menu does. To do this my control needs to get notified when the user tried to click off of it. The Leave and LostFocus events of the UserControl work most of the time but not always. For example, if they click on a part of the form...
2
2188
by: david | last post by:
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway, although Ollie's answer makes perfectly sense when dealing with classes, it doesn't seem to me to apply as well if you have to instantiate an array of structures; consider the following useless code : using System; struct MyPointS
2
3159
by: Joey | last post by:
Hi There, I am trying to get the selected value of a listbox when I click a button, everything works ok and I can bind the list and when I have a basic page and click a button to invoke a sub it works fine, but when I try to place it in the sub I want to use it give me an eror saying that the "Object reference not set to an instance of an object." I can't understand why it works in a small sub in the same class but then when I try to use...
14
2116
by: Lars Netzel | last post by:
A little background: I use three Datagrids that are in a child parent relation. I Use Negative Autoincrement on the the DataTables and that's workning nice. My problem is when I Update these grid and write to the database and I set the new Primary Keys and related Fields to the new asigned atuonumbers in the Access.
1
1962
by: Michael D. Reed | last post by:
I am using the help class to display a simple help file. I generated the help file using Word and saving it as a single page Web page (.mht extension). I show the help file with the following statement. Help.ShowHelp(Parent:=Me, url:=Me.HELP_URL_PRE & Me.myWorker.HelpFile) How do I get it to go away when the program exits? Now when I quit the program that I called it form the help file is sill displayed. Is there a way to get a handle...
9
6048
by: Simon | last post by:
Hi, I have written an ActiveX object to resize images and upload them to a database, this all works fine but when I close internet explorer the process iexporer.exe is still running in my task manager and I can not launch anything from the desktop (eg. a web shortcut) without firt killing this process. The object is launched using JScript with the following code: var Launcher = new ActiveXObject("LaunchControl");
11
3245
by: MikeT | last post by:
This may sound very elementary, but can you trap when your object is set to null within the object? I have created a class that registers an event from an object passed in the constructor. When my object is destroyed, I want my object to un-register this event. If I don't then the object would never be destroyed until the object I passed in the constructor is destroyed. I have implemented a Dispose(), Dispose(bool), and ~Finalize...
0
2183
by: raylopez99 | last post by:
I ran afoul of this Compiler error CS1612 recently, when trying to modify a Point, which I had made have a property. It's pointless to do this (initially it will compile, but you'll run into problems later). Apparently Point is a struct, a value type, and it does not behave like a classic structure (in my mind's eye, and see below). Traditionally I think of a classic structure as simply an object where every member is public. But with...
0
8172
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8677
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
8620
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...
0
8474
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
7158
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...
0
4079
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...
1
2605
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
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1482
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.