-
C++ Object heap stack
I have a doubt .. consider the below situation
Code:
object a;
object b;
b=a;
now what happens to the memory thats allocated to object b ... and am I right in saying that the memory for the objects in the above example gets created on the stack..
thanx in advance
-
-
When you define the object b (object b;), storage is allocated for b. When you later initialize it (b = a), you simply access the memory space of b and insert the value of a.
However, you don't use the heap. The heap (or free store) is used when you dynamically allocate memory with the use of the new expression.
-
That post at cppworld confuses me...
Isn't what the author calls "global data" also part of the stack?
-
If you are talking about an object of class type, it also depends on behaviour of the class. If the class assigns memory dynamically, some memory is on the "stack" (in common parlance, which I consider rather useless) and some is not.
The assignment "b=a" will typically invoke a function named object::operator=() which takes a reference to object as an argument. The catch is that the compiler supplied default version of that function (supplied if the programmer doesn't supply one) simply copies individual members of a into b by value. That can cause errors if the class manages (say) memory resources: in that case the assignment operator needs to ensure that the assignment does not (direclty or indirectly) cause a memory leak or undefined behaviour.
For example;
Code:
class object
{
public:
object() : x(new int) {};
~object() {delete x;};
private:
int *x;
};
int main()
{
object a;
object b;
b = a;
}
will cause undefined behaviour, as the result of the assignment is object's destructor will destroy the same memory (a.x) twice (once when a is destroyed, once when b is destroyed). This needs to be fixed, for example;
Code:
class object
{
public:
object() : x(new int) {};
object &operator=(const object &a) {*x = *(a.x);};
~object() {delete x;};
private:
int *x;
};
int main()
{
object a;
object b;
b = a;
}