Terms: HEAP vs STACK
Your question should be named "how to create object copy". One reason is that original object location doesn't matter, creating copy from object on stack and from object on heap are pretty much the same. The second reason is that your current code tries copying object pointed by someFunction()
return value which may have sense only if someFucntion()
creted object on heap. Otherwise, if someFunction()
created object on stack like this:
someStruct tmp;
tmp.num = 5;
return &tmp;
then once someFunction()
finishes execution, its stack frame is freed and might be reused for other functions stacks. Thus 'tmp' structure is located in memory, which can be overwritten any moment, so you can't rely on its data. Never use pointer to local variables after local variable goes out of scope.
Copying object
Well, your ATTEMPT 1 is fine. Using new
for creating class or structure calls constructor to build object. You passed another object as parameter, so copy constructor is called. You didn't write copy constructor, but compiler created trivial one automatically, so it correctly copied all fields from original object to newly created.
However, cout
didn't show expected output due to bug in another part of the program. Calling foo(a);
means passing copy of a
as a parameter to foo
. So you don't change main
's a
value within foo
, but change value of foo
's copy of a
. On return to main, a
is still NULL
and can't be dereferenced. As minimal fix, you need to pass a
(which is already pointer, so it's a bit confusing) by pointer or by reference instead of passing it by value. Example:
int main() {
someStruct *a = NULL;
bool ret;
ret = foo(&a);
std::cout << a->num; // should print 5
delete a;
return ret;
}
bool foo(someStruct **x) {
someStruct *b = someFunction(); // points to an instance of someStruct on the heap
*x = new someStruct(*b);
delete b;
return true;
};
Make a good habit of calling delete
eventually for each dynamically allocated buffer, memory leakages may become quite painful on larger programs.