I am using std::map, similar to the implemtentation in webrtc (see here). My Map is defined like that:
typedef std::map <std::string, BaseOption*> OptionMap;
And the BaseOption (Option) is defined:
class BaseOption {
public:
virtual ~BaseOption() {}
};
template<typename T>
class Option : public BaseOption {
public:
explicit Option(T* v) {value = v;}
~Option() { delete value; }
T* value;
};
The Set-Member:
template<typename T>
void ClassFoo::Set(OptionIdentifier option_, T* value) {
BaseOption*& option_member = options_[option];
delete option_member;
option_member = new Option<T>(value);
}
I call fill the map from a class-member called put_into_map (just a quick-and-dirty implementation to test my class):
void ClassFoo::put_into_map(){
int tempval = 8000;
this->Set<int>("IeAIf", &tempval);
this->Set<int>("LcE8V", &tempval);
tempval = 16000;
this->Set<int>("RVn1C", &tempval);
this->Set<int>("XINa2", &tempval);
tempval = 1;
this->Set<int>("st6Vz", &tempval);
this->printAll<int>();
}
And used from main:
int main(){
ClassFoo foo_object = new ClassFoo();
foo_object->put_into_map();
return 0;
}
The printAll works like:
template<typename T>
void ConfTool::printAll(){
std::cout << "#Elem in Map " << this->options_.size() << std::endl;
OptionMap::const_iterator it;
for (it = options_.begin(); it != options_.end(); ++it)
{
std::cout << "Arg: " << it->first << " Value: \t" << static_cast<Option<T>*>(it->second)->value << std::endl;
}
}
Inserting different stuff into the map, and dumping it (or useing it), all Options have the same value. Also dumping the addresses behinde these values, the same spaces gets shown (inserted some random Data):
Arg: IeAIf Value: 0x7fffc49980cc
Arg: LcE8V Value: 0x7fffc49980cc
Arg: RVn1C Value: 0x7fffc49980cc
Arg: XINa2 Value: 0x7fffc49980cc
Arg: st6Vz Value: 0x7fffc49980cc
I assume that I failed to design the Set-Member in a correct way.
答案 0 :(得分:2)
您需要重新考虑您的设计。由于您在&tempval
中存储了相同的指针(Option::value
),因此在输出中得到相同的指针。
如果您打印it->second
,您会看到此特定指针不同。但是当你得到value
,即(it->second)->value
时,你最终会得到&tempVal
,就像你编码它一样。
换句话说,程序完全按照描述进行 - 你存储了一个指针,你将获得指针。您的设计中没有任何内容“提取”位于指针的值并将其放在新的Option实例中。
以下是代码的最小示例:http://ideone.com/jn5GtU
请注意it->second
所占据的地址正在发生变化,但it->second->value
不会发生变化。它也恰好是&tempVal
。