开发者

When object is constructed statically inside a function, would it be allocated on the heap or on the stack?

if i have the foll开发者_运维知识库owing code:

for (...) { A a; }

would a be allocated on the heap or on the stack?


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.


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++).


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 newed and deleteed.


A will be allocated entirely on the stack. A may, of course, allocate memory from the heap during its construction.


Static and const variables are placed on stack in special area.


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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜