Re: Automatic and Dynamic Storage
On May 14, 7:37 am, V <vdu...@gmail.com> wrote:
class B {
public:
B() {
std::cout << "B()\n";
}
~B() {
std::cout << "~B()\n";
}
private:
A a;
};
Now, if I write:
B *ptr = new B();
the object of type B pointed by "ptr" has "dynamic storage duration",
or, in other words, is stored into the heap (Herb Sutter's talk of
"free store", but this is not the point of this question). Now, inside
B there is the data member "a", that has "automatic storage duration".
No, "a" is a -member- variable, meaning that "a" is not an
independently-allocated variable - but is instead allocated as part of
another variable. So whether "a" has dynamic or automatic storage -
depends on whether the complete object of which it is a part ("ptr" in
this example) has dynamic or automatic storage. Therefore, since "ptr"
is dynamically allocated, the ptr->b member variable is dynamically
allocated as well. In fact, part (or likely, all) of the memory
allocated for the "ptr" B object is in fact occupied by its "a" member
variable.
But if "a" has automatic storage duration, it's stored into the stack?
In my opinion no: rather, I think that is stored "somewhere else".
But "ptr->a" does not have automatic storage in this case, because
"ptr" does not have automatic storage.
So, quoting Herb Sutter, we can say that "the stack stores automatic
variables", but "not all automatic variables are stored into the
stack".
No, saying that automatic variables are always allocated on the stack
would certainly be an accurate statement much more often than not.
Question #1: is my deduction correct?
No.
Question #2: if data member "a" is not stored into the stack, where
else can be stored?
Since "a" is part of B, "a" is stored wherever the B object itself is
stored - whether on the heap or on the stack.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]