(不确定此标题是否是最佳说明...)
大家好。我需要以下代码的帮助。在process
函数中,我希望cc
和cc_sub
(作为cc
中的字段获取)显示不同的内容(它们最初是这样做的),但它们显示相同的内容。 Storage
实例是在makeObj
函数中创建的。有人可以告诉我怎么了,如何解决这个问题?谢谢。
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;
:
}
最佳答案
您看到的奇怪行为是由于在Storage
和setData
中都操纵了makeObj
临时变量。这种操纵的结果在C++中是不确定的。
请尝试以下操作:
void process(const Storage cc) {
Storage cc_sub = *((Storage*)cc.data);
cout << ... << endl;
}
class Storage {
public:
Storage() {
this->data = NULL;
}
Storage(const Storage& obj) {
this->data = obj.data;
}
void* data;
void setData(Storage* dPtr) {
this->data = dPtr;
}
};
Storage* makeObj(std::string* s) {
// Allocate memory on the heap so that cc lives beyond this function call
Storage* cc = new Storage;
:
// Populate the sub-storage with a heap-allocated variable
cc->setData(makeObj(&subString));
return cc;
}
请注意,当前编写的
makeObj
代码如果被调用将导致堆栈溢出,因为它无法结束其递归...为了cHao的建议,这是使用
shared_ptr
(Microsoft Visual Studio 2008版本-您可能需要更改#include <memory>
和/或std::tr1::shared_ptr
,具体取决于您的编译器)的更完整程序。我将数据类型从void*
更改为Storage
(shared_ptr
),并添加了一个字符串成员以更好地显示差异:#include <string>
#include <iostream>
#include <memory>
using namespace std;
using namespace std::tr1;
class Storage {
public:
Storage() {
}
Storage(const Storage& obj) {
this->data = obj.data;
}
string s;
shared_ptr<Storage> data;
void setData(shared_ptr<Storage> dPtr) {
this->data = dPtr;
}
};
void process(const shared_ptr<Storage> cc) {
shared_ptr<Storage> cc_sub = cc.get()->data;
cout << "Parent string: " << cc.get()->s << endl <<
"Child string: " << cc_sub.get()->s << endl;
cout << "Parent data pointer: " << cc.get()->data << endl <<
"Child data pointer: " << cc_sub.get()->data << endl;
}
shared_ptr<Storage> makeObj(string* s) {
shared_ptr<Storage> cc(new Storage);
if (s->length() != 0) {
string subString = s->substr(0, s->length()-1);
cc->s = subString;
cc->setData(makeObj(&subString));
}
return cc;
}
int main(int argc, char* argv[]) {
string s = "hello";
shared_ptr<Storage> storage = makeObj(&s);
process(storage);
return 0;
}