(Not sure if this title is the best description…)
Hi all. I need a help with the following code. In process function, I want cc and cc_sub (which is obtained as a field in cc) to show different contents (as they are originally made so) but they show the same. Storage instances are made in makeObj function. Could someone tell me what’s wrong and how to work this around? Thank you.
Int process(const Storage cc) {
Storage cc_sub = (Storage&) cc.data; // Here
cout << ... << endl; // Contents from cc and cc_sub are the same though they are not supposed to be.
}
class Storage {
public:
Storage() {
this->data = NULL;
}
Storage(const Storage& obj) { //Copy Constructor. Result is the same even if I removed this entire clause.
this->data = obj.data;
}
void* data;
void setData(Storage dPtr) {
this->data = &dPtr;
}
};
Storage makeObj(std::string* s) { // I want to keep the return value as value instead of pointer,
// since when it returns pointer the values pointed by reference behaved unexpectedly (guess it's because of temporary object type of error)...
Storage cc;
:
cc.setData(makeObj(&subString));
return cc;
:
}
The odd behavior you’re seeing is due to manipulating temporary
Storagevariables, both withinsetDataandmakeObj. The outcome of such manipulation is undefined in C++.Try the following:
Note, the code as currently written
makeObjwill cause a stack overflow if called as it has no way of ending its recursion…To cHao’s suggestion here’s a more complete program using
shared_ptr(Microsoft Visual Studio 2008 version – you may need to change#include <memory>and/orstd::tr1::shared_ptrdepending on your compiler). I’ve changed the type of the data fromvoid*toStorage(shared_ptr) and added a string member to better show the differences: