"voidtwerp" <vo*******@gmail.comschrieb im Newsbeitrag
news:11*********************@v61g2000cwv.googlegro ups.com...
Hi,
I hope this is not too OT but I would like clarification on how classes
are held in memory.
each object obviously has an individual copy of its data.
I guess a class would only have one copy of its functions held in
memory (not sure what part of memory this would be refered to as).
So far your guess is close enough. And as C++ itself does not give that
memory a name (that I can remember) I won't give it a name either. Functions
are just a part of the program and the program can access them.
Then whenever an object has a function called on it this function would
be copied onto the stack - am I right?
No. As far as C++ is concerned, functions are not copied anywhere. They are
just there. The OS may load the code from disk if it thinks that to be
usefull, but usually you don't have to worry about that. And even if the
code would be copied, no decent OS would copy them onto a stack. Most OS
even take special care that whatever is on the stack or in any other piece
of memory, that is used for data storage, will never be executed. But that's
a matter of system secuitity and not of C++.
What usually is allocated on a stack (even though C++ does not require it to
be a stack) are local variables. These variables are allocated when
execution reaches the point where they have been defined in the code and
they will be destroyed when execution leaves the smallest enclosing scope.
But then this should cause problems if the returned pointer is used
after the function has been replaced on the stack but it works
perfectly well - so what exactly is stored where?
This is indeed a problem for local variables. You must never return a
pointer or reference to a local variable.
char * MyClass::MyFunc(int selection)
{
switch(selection)
{
case 1:
return "one";
case 2:
return "two";
default:
return "no selection";
}
}
String literals are no local variables. You can think of them as global
constants which are available as long as the program runs. So it is ok to
have a function
char const* Foo()
{
return "foo";
}
But you should never try
char const* Bar()
{
char bar[] = "bar";
return bar;
}
And to add even more confusion, you can do
char const* Baz()
{
char const* baz = "baz";
return baz;
}
Foo is ok because it simply returns the address of something global. Baz is
ok too. It takes the address of something global, stores it in a local
variable, and finally returns a copy of this address, which still points to
something global. Bar, however, creates a local variable, initializes it
with a copy of a global string, and than returns the address of the local
variable.
HTH
Heinz