std::map error

Started by
5 comments, last by ToohrVyk 14 years, 11 months ago
Hello. This is valid in std::map:

std::map <int, int> m;
m[1] = 1000;

The type is: map<string, boost::weak_ptr<Animation> > /*typedef boost::weak_ptr<Animation> registry_entry_type; typedef std::map <std::string, registry_entry_type> registry_type; registry_type _AnimationMap;*/

_AnimationMap[category] = boost::weak_ptr <Animation> ( new Animation() );

I get: error C2440: '<function-style-cast>' : cannot convert from 'Min::Animation *' to 'boost::weak_ptr<T>' 1> with 1> [ 1> T=Min::Animation 1> ] 1> No constructor could take the source type, or constructor overload resolution was ambiguous
Advertisement
weak_ptr documentation states that you can construct weak_ptr object only from shared_ptr object (and of course from another weak_ptr with copy constructor). But not from T*.
I don't think you can have a weak_ptr handle a raw pointer.
Read the boost docs here

It says : "The weak_ptr class template stores a "weak reference" to an object that's already managed by a shared_ptr."
Edit: Too slow [looksaround]
This has nothing to do with std::map. The problem is that you are trying to cate a weak pointer from a naked pointer, which is impossible. You can only create a weak pointer from a shared pointer.
I changed weak_ptr to shared_ptr and it works fine, thank you :)
Well, stop and think carefully about what the pointer semantics are.

shared_ptr means "I am taking part in keeping the pointed-at object alive". As long as anyone has a shared_ptr to the object, it won't be deleted.

weak_ptr means "I am not accepting any responsibility for the lifetime of this object; I only want to be able to get at it while it's alive". You can't have *everyone* hold a weak_ptr because then there is no way to decide when the object should die. That's why you can't make a weak_ptr to the newly allocated object: it's too easy to end up without a shared_ptr.
Quote:Original post by Zahlman
You can't have *everyone* hold a weak_ptr because then there is no way to decide when the object should die.
It would make sense to destroy the object as soon as a weak pointer is created from it—although that would be pretty useless and error-prone.

This topic is closed to new replies.

Advertisement