stack vs heap

Started by
30 comments, last by King Mir 11 years, 1 month ago

I'm a little confused ;)
Can you please tell me, in the next example, mainCanon is in the heap or stack?

On the heap, fella. The Army instance created with new contains the array of tanks, which each contain the Canon instance so the whole lot is on the heap.

You can't tell from looking at a class definition where the data members will end up. You have to look at where the instance, or the containing instance etc is created.

[EDIT] "On the heap" as in dynamically allocated and not subject to automatic scope lifetime. As has been covered already, the compiler is not bound to implement this as a heap in any normal sense of the word.

Advertisement

They have the same lifetime. So instead of saying that foo has a "stack lifetime", it's better to say that it has an "automatic lifetime" (which means it's lifetime is the same as it's scope/{})

I don't think that's quite right. Automatic lifetime refers to variables that could, prior to C++11, be qualified with the auto keyword. This does not include class data members. They would be contrasted with variables with static, register, or extern storage classes.

What you describe would suggest a misleading parallel between class data members and function variables. In particular this is misleading when either is qualified with static, because static class data members and static function variables behave differently. As inherited from C, static function and global variables make the variable local to the translation unit. Static class data members behave more like extern qualified variables and are per-project.

This topic is closed to new replies.

Advertisement