铸造指针
我使用 ptr_map 来存储不同类型的指针。
boost::ptr_map<string, any> someMap;
我在那里存储一些模板化的类对象:
someMap.insert("1", new SomeClass<int>());
someMap.insert("2", new SomeClass<float>());
现在我想从地图获取值。这是一个带有引用的示例:
template<typename T>
T &get(const string &someKey)
{
try
{
return any_cast<EventType&>(mSignalAssociation.at(signalName));
} catch(bad_any_cast &e)
{
// Logging here
}
}
get< SomeClass<int> >("1"); // This works
但我不喜欢引用,因为我无法返回,例如,如果转换错误或对象不存在,则无法返回 NULL。
如何从该地图获取指针?
T *get(const string &someKey)
{
return any_cast<EventType*>(mSignalAssociation.at(signalName));
}
可以构建,但铸造失败,为什么?
I'm using ptr_map for storing different types of pointers.
boost::ptr_map<string, any> someMap;
I store there some templated class objects:
someMap.insert("1", new SomeClass<int>());
someMap.insert("2", new SomeClass<float>());
Now I want to get values from map. Here is a sample with references:
template<typename T>
T &get(const string &someKey)
{
try
{
return any_cast<EventType&>(mSignalAssociation.at(signalName));
} catch(bad_any_cast &e)
{
// Logging here
}
}
get< SomeClass<int> >("1"); // This works
But I don't like references, because I can't return, for example, NULL if the casting is bad or the object doesn't exist.
How can I get pointer from this map?
T *get(const string &someKey)
{
return any_cast<EventType*>(mSignalAssociation.at(signalName));
}
This builds but fails at casting, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个怎么样:(
只是猜测)
how about this:
(Just a guess)
您想要的是指针语义。还要停止使用 ptr_map,正如评论中指出的那样,这是一种浪费。
如果您出于某种原因需要存储指向这些 SomeClass 对象的指针,那么我认为您必须自己进行内存管理(手动释放存储在 any 中的元素)并使用额外的间接级别来检测 null 的强制转换失败指针。如果你这样做的话,最好使用像 boost::shared_ptr 这样的东西。
What you want are the pointer semantics. Also stop using ptr_map, it's a waste as has been pointed out in the comments.
If you need to store pointers for some reason to these SomeClass objects, then I think you'll have to do the memory management yourself (manually free the elements stored in any) and use an extra level of indirection to detect cast failures with a null pointer. Probably better to use something like boost::shared_ptr if you do.
啊...这就是为什么你要使用指针、引用、转换和内存管理容器进行这些练习的原因! :)
正如我之前指出的之前;这会带来不必要的麻烦。
幸运的是,您的问题已经解决 - 只需查看 增强。可选。
Ah... so that is the reason why you are doing these gymnastics with pointers, references, casting and memory managing containers! :)
As I pointed out previously; this will create unnecessary headaches.
Fortunately, your problem has been solved - just look at Boost.Optional.