Hello,
I think dynamic memory allocation is supposed to be used when one
doesn't know in advance how much memory to allocate until run time. An
example from Thinking in C++ is to dynamically create an array (using
"new") since one doesn't know it size when writing the program.
However, it looks to me that the size information must come from
somewhere at run time, and this information can be passed to array
creation function as a function's formal argument. Therefore, the
array can still be created using a "static" method. Is this right?
I'd really appreciate it if someone could advise me when to use dynamic
memory allocation.
Many thanks!
xian 13 4721
xian_hong2046 wrote: I think dynamic memory allocation is supposed to be used when one doesn't know in advance how much memory to allocate until run time.
Use it if you don't know if you will need an object or not, and if the
object's lifespan must last longer than the function that creates it.
Otherwise, put the object on the stack. It also dynamically allocates, but
synchronized with method calls so you don't need to explicitely delete
things.
An example from Thinking in C++ is to dynamically create an array (using "new") since one doesn't know it size when writing the program.
That is a "Thinking in C" topic, because functions like malloc() are the
only way to create a variable-size array in C.
Read /Accelerated C++/, and use std::vector<> to create an array of variable
size. No 'new' or 'delete'. The vector hides them, making your job much
easier and your code much safer.
However, it looks to me that the size information must come from somewhere at run time, and this information can be passed to array creation function as a function's formal argument. Therefore, the array can still be created using a "static" method. Is this right?
No, because both C and C++ use low-level arrays that are as close to the
metal as possible. Look at this function:
void foo()
{
char slug[99];
...
}
The compiler must know, at compile time, how big to make the foo()
function's stack frame. That's so that (on common implementations ) the
compiler can generate the simplest and fastest possible opcodes to create
that stack frame, when foo() starts.
That's why C++ should not permit this:
void foo(int amount)
{
char slug[amount];
....
}
'amount' is not a "hard constant", or "compile time constant". The compiler
cannot guess how big foo's stack frame will be, so it refuses to generate
slower opcodes that calculate this size.
The C languages often make the programmer work a little harder so the
compiler and its output code can work easier and faster.
I'd really appreciate it if someone could advise me when to use dynamic memory allocation.
This is uncompiled code that might contain syntax errors, but it will get
you started:
typedef std::auto_ptr<S imCity> SimCityPointer;
SimCityPointer cityFactory(str ing type)
{
if ("skyscraper s" == type)
return SimCityPointer( new SkyScraperCity) ;
if ("ecotopic" == type)
return SimCityPointer( new EcotopicCity);
if ("shanty" == type)
return SimCityPointer( new ShantyCity);
return SimCityPointer( new NullCity);
}
All the *City classes inherit SimCity.
If the user provides a string for what city they want, we create one and
return it.
The calling functions don't care what kind of city it is, hence they can't
create it themselves. If they could, they might put it on the stack, and not
use 'new'.
Because this function decouples the city creation system from the other
functions, it must safely call 'new', and then ensure that functions who use
the city will indeed call 'delete' on it when they are finished with it.
When you call 'new', you should immediately provide a 'delete'. Don't put
that off or try to remember, later after you write many more client
functions, to write a 'delete'. I provided for a delete by putting the
pointer inside the template std::auto_ptr<> .
Discard any C++ tutorial that doesn't discuss smart pointers!
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Hi Phlip,
Many thanks for your detailed explanation, that really helped!
xian
In article <11************ **********@e56g 2000cwe.googleg roups.com>,
"xi***********@ hotmail.com" <xi***********@ hotmail.com> wrote: Hello,
I think dynamic memory allocation is supposed to be used when one doesn't know in advance how much memory to allocate until run time. An example from Thinking in C++ is to dynamically create an array (using "new") since one doesn't know it size when writing the program.
Those kinds of issues are addressed in the standard library. If you
don't know how many objects you need until runtime, use a container.
I'd really appreciate it if someone could advise me when to use dynamic memory allocation.
You should use dynamic memory allocation directly when you don't know
the *type* of the object you are creating until runtime.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
In article <mz************ *****@newssvr33 .news.prodigy.c om>,
"Phlip" <ph******@yahoo .com> wrote: xian_hong2046 wrote:
I think dynamic memory allocation is supposed to be used when one doesn't know in advance how much memory to allocate until run time.
Use it if you don't know if you will need an object or not, and if the object's lifespan must last longer than the function that creates it.
I think that the above isn't general enough. For example, a constructor
can create an object, and the destructor destroy it, without it being
newed or deleted.
I was think of some rule like "if the scopes don't match" but you can
always create a scope that matches the objects lifetime so that doesn't
work either... I'd really appreciate it if someone could advise me when to use dynamic memory allocation.
This is uncompiled code that might contain syntax errors, but it will get you started:
typedef std::auto_ptr<S imCity> SimCityPointer;
SimCityPointer cityFactory(str ing type) { if ("skyscraper s" == type) return SimCityPointer( new SkyScraperCity) ;
if ("ecotopic" == type) return SimCityPointer( new EcotopicCity);
if ("shanty" == type) return SimCityPointer( new ShantyCity);
return SimCityPointer( new NullCity); }
All the *City classes inherit SimCity.
If the user provides a string for what city they want, we create one and return it.
The calling functions don't care what kind of city it is, hence they can't create it themselves. If they could, they might put it on the stack, and not use 'new'.
Because this function decouples the city creation system from the other functions, it must safely call 'new', and then ensure that functions who use the city will indeed call 'delete' on it when they are finished with it.
The above is a good explanation but it doesn't match the general rule
given, your using 'new' because you don't know what type of city you
will need until runtime, not because it outlives the function.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Daniel T. wrote: Use it if you don't know if you will need an object or not, and if the object's lifespan must last longer than the function that creates it. I think that the above isn't general enough. For example, a constructor can create an object, and the destructor destroy it, without it being newed or deleted.
I was think of some rule like "if the scopes don't match" but you can always create a scope that matches the objects lifetime so that doesn't work either...
The goal here is to find just the right verbiage that leads no newbie
astray, but doesn't depend on the advanced terms like "scope" or "RAII" or
"determinis tic destruction".
So, "don't call 'new' until you exhaust the simpler alternatives", and
"vector is simpler than new[] for arrays".
The above is a good explanation but it doesn't match the general rule given, your using 'new' because you don't know what type of city you will need until runtime, not because it outlives the function.
Right. I'm so advanced that I can't think of the simplest possible scenario
that demands 'new'.
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
In article <4s************ *******@newssvr 30.news.prodigy .com>,
"Phlip" <ph******@yahoo .com> wrote: Daniel T. wrote:
The above is a good explanation but it doesn't match the general rule given, your using 'new' because you don't know what type of city you will need until runtime, not because it outlives the function.
Right. I'm so advanced that I can't think of the simplest possible scenario that demands 'new'.
:-) I disagree, you aren't that advanced. That *is* the simplest
possible scenario that demands 'new'. The only time that 'new' is
demanded is when you don't know what sub-type to make until runtime.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Hi Daniel and Phlip,
Thanks to both of you for the discussions, I find them very useful
indeed.
May I please ask you another two questions, which may be quite trivial
to you?
I had a simple file like:
#include <iostream>
using namespace std;
int i;
i = 10;
int main(){
cout << i << endl;
}
But it couldn't compile. However, if I combined the declarations and
definitions of "i" into one:
int i = 10
then it all worked out. It also worked if I moved "i=10" into the body
of "main". What's the problem?
Another question concerns the use of "extern". It should be used when
one declares a function or variable that has been defined in another
file or will be defined later in this file. If the variable/function
is declared in a .h file (but no definitions are provided in the .h
file), then after I include the header file, do I still need to use
"extern" before I use that function/variable? From my experiments, it
looks like I don't have to. But according to the purpose of "extern",
it seems that I should use "extern".
Many thanks,
xian
Daniel T. wrote: The only time that 'new' is demanded is when you don't know what sub-type to make until runtime.
A. What example would you give an absolute new newbie?
B. I'm certain I have used new for simpler situations. I'm aware
some of them could have been NullObjects, or the equivalent.
Are you convinced that's the _only_ time new is demanded??
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!! xi***********@h otmail.com wrote: int i;
i = 10; int main(){ cout << i << endl; }
Only declarations, definitions, and initializations may appear outside of
functions or constructors. (And namespaces, typedefs, preprocessor
statements, and other bric-a-brac that some language lawyer wannabe is sure
to jump all over me about.)
This is permitted outside of functions:
int i = 10
i = 10; is not because it's not part of the action of defining x.
Initialization is.
Another question concerns the use of "extern". It should be used when one declares a function or variable that has been defined in another file or will be defined later in this file. If the variable/function is declared in a .h file (but no definitions are provided in the .h file), then after I include the header file, do I still need to use "extern" before I use that function/variable? From my experiments, it looks like I don't have to. But according to the purpose of "extern", it seems that I should use "extern".
It's optional on function declarations and not
The deal here is a "translatio n unit" that's usually one .cpp file that
creates one .o or .obj file. After you put all the .h files together
into .cpp file, the result is a "translatio n unit" that then gets compiled
into opcodes.
For a given global int Foo, all translation units that need the Foo should
see an 'extern int Foo;'. But only one translation unit needs 'int Foo =
42;'. That's so the opcodes that create the Foo itself will only compile in
one spot, and only go into one .o or .obj file.
Now don't use extern, and learn not to make global variables. Make global
functions instead, so the code stays more flexible. Many thanks, xian
--
Phlip http://www.greencheese.org/ZeekLand <-- NOT a blog!!! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: New |
last post by:
I am new to java and was wondering does java have dynamic memory allocation
like in C (malloc, calloc)
Thank you
|
by: Steven T. Hatton |
last post by:
In the following code, at what point is S::c fully defined?
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
class C {
int _v;
|
by: chris |
last post by:
Hi all,
I need to know, what is the difference between dynamic memory
allocation, and stack allocation ?
1. If I have a class named DestinationAddress, when should I use
dynamic memory allocation to create object of that class ?
2. If it says "dynamic memory allocation", is it mean the
following code :
DestinationAddress* dest = new DestinationAddress(); // code 1
|
by: Sandeep Chikkerur |
last post by:
Hi,
If the entire heap memory for dynamic allocation is not available,
does the compiler always return NULL ?
eg:
char *s;
s = (char *)malloc(...);
|
by: chai |
last post by:
Can anyone help me in finding elements stored in a dynamic array in.
| |
by: Ken |
last post by:
In C programming, I want to know in what situations we should use
static memory allocation instead of dynamic memory allocation. My
understanding is that static memory allocation like using array is
faster than malloc, but dynamic memory allocation is more flexible.
Please comment... thanks.
|
by: ranjeetasharma81 |
last post by:
Hi all,
I have a big C-cod, in which there are lots of dynamic memory allocation used. I want to replace dynamic memroy allocation by static arrays. The following are the problems that i am facing:
1- From structure and dynamic memory allocation point of view, the code is
very complicated. The code has various “nested structures” with a number
of levels. The size of memory allocated for pointer to structure or its
pointer...
|
by: vivek |
last post by:
i have some doubts on dynamic memory allocation and stacks and heaps
where is the dynamic memory allocation used?
in function calls there are some counters like "i" in the below
function. Is this stored in stack. If yes whether it will be deleted
on exiting from the function.
is dynamic memory allocation needed for this purpose
|
by: arnuld |
last post by:
I have created a program to print the input words on stdout. Input is
taken dynamically from stdin. In each word, each input character is
allocated dynamically. I have ran this program with a file containing a
*single* word made of 25525500 letters and this program works fine on it.
I will welcome any suggestions for improvement.
/* * A program that will ask the user for input and then will print the words on stdout
* and will also...
|
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...
|
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,...
| |
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...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |