Re: Automatic and Dynamic Storage
On 2008-05-14 16:37, V wrote:
Hi,
I now that C++ has no concept of stack or heap, but use the more
abstract "automatic storage" and "dynamic storage" definitions
(section 3.7 of the standard). Normally, I think that automatic
storage objects are stored in the stack, and dynamic storage objects
are stored in the heap. Also Herb Sutter, in his "Exceptional C++",
item #35, said that: "the stack stores automatic variables".
Said so, suppose we have those simple classes:
class A {
public:
A() {
std::cout << "A()\n";
}
~A() {
std::cout << "~A()\n";
}
};
and:
class B {
public:
B() {
std::cout << "B()\n";
}
~B() {
std::cout << "~B()\n";
}
private:
A a;
};
(note that B has a data member "a" of type 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".
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".
So, quoting Herb Sutter, we can say that "the stack stores automatic
variables", but "not all automatic variables are stored into the
stack".
Question #1: is my deduction correct?
Yes, just because a variable has automatic storage duration does not
mean that it is stored on the stack.
Notice that the standard talks about automatic or dynamic storage
*duration*, in other words it is only concerned about the lifetime of
the object and not where it is stored. This means that an implementation
can store all variables on the stack or on the heap (as long as they can
make the program behave correctly).
Question #2: if data member "a" is not stored into the stack, where
else can be stored? (Ok, this is an implementation-dependent question,
but I'm interested into the "ideas" behind this.)
Notice that "a", as a member of the B object, is a part of the B object.
Members are store with the objects they are members of (while I don't
know the chapter and verse in the standard I'm quite sure that this is
required).
A more interesting example would be
#include <iostream>
struct A {
A() { std::cout << "A()\n"; }
~A() { std::cout << "~A()\n" }
};
struct B {
A* aPtr;
B() : aPtr(new B()) { std::cout << "B()\n"; }
~B() { delete aPtr; std::cout << "~B()\n"; }
};
int main() {
B b;
}
In this case "b" has automatic storage duration but the A object has
dynamic duration. Notice though that "aPtr" still has automatic duration.
--
Erik Wikstr??m
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]