if i have the following code:
for (...) { A a; }
would a be allocated on the heap or on the stack?
if i have the following code:
for (...) { A a; }
would a be allocated on the heap or on the stack?
On the stack.
Memory is only allocated on the heap when doing new
(or malloc
and its friends if you are doing things C-style, which you shouldn't in C++).
When you say:
for (...) { A a; }
the variable a is NOT being constructed statically. That would be:
for (...) { static A a; }
In fact in your code, a is an automatic object, created on the stack. However, that doesn't mean that no dynamic allocation is taking place. If A looked like this:
struct A {
A() { p = new char[100]; }
char *p;
};
then when you say :
for (...) { A a; }
the storage for a.p is created on the stack, but the storage that a.p points at is created dynamically.
You are not declaring a static
variable in your code - it is a locally scoped variable and thus it will end up on the stack.
That's not a static variable. Also A is allocated on the stack.
Variables are allocated on the heap only when explicitly new
ed and delete
ed.
A will be allocated entirely on the stack. A may, of course, allocate memory from the heap during its construction.
Hi Eric
the variable is created on the stack. In your code :
for (...) { A a; }
...And then at the end of any "for" cycle, the variable is destroyed automatically (because it goes out of scope), as Neil said:
Neil Butterworth : In fact in your code, a is an automatic object...
But if the a object makes some dynamic allocations (IOW, on the heap) during his own life cycle, then be aware to free the memory by yourself, or in the destructor of A, or outside. C example :
struct A {
A(char *ptr);
~A();
private:
char *p;
int len;
};
A::A(char *ptr)
{
len = strlen(ptr);
p = (char *) malloc(len+1);
if(!p) {
exit(1);
}
strcpy(p, ptr);
}
A::~A()
{
free(p);
}
The p variable is not freed automatically if you don't call the free procedure.
Bye (and sorry for my english)
PS : i would like to say that the word "statically" so severly criticized in this context, it is not so bad as they jkp and jldupont ...
jkp : "The word "statically" is a bit misleading there, it implies usage of the static keyword...."
jldupont : "You are not declaring a static variable...."
and so on...
jkp and jldupont are 100% right but in italian technical language some C++ programmers use the word "created statically" and "built statically" to identify a variable will be created on the stack
When you define a static variable instead, in other words
static A a;
The same programmers use to call that "static variable" and "variable declared as static".