My problem is that I don't want to force
example.foo()
to be called only with example objects that are owned by a shared_ptr.
How do you expect to pass a shared_ptr
to bar
if the object isn't owned by a shared_ptr
? Do you want to pass a n empty shared_ptr
?
You could do nasty things with the aliasing constructor of shared_ptr
but I wouldn't recommend it.
Please correct me if I'm mistaken.
You're not mistaken, enable_shared_from_this<T>::shared_from_this()
has a precondition that at least one shared_ptr
owns the object.
In case I'm not mistaken, how can I get this over?
There is no portable way to avoid that, because it's a precondition, and you must not violate preconditions, however this might "work" (for some value of work):
void example::foo ()
{
shared_ptr<example> ptr;
try {
ptr = shared_from_this(this);
} catch (boost::bad_weak_ptr const&) {
}
bar(ptr);
}