Detect if an object belongs to a smart pointer


I have a class which derives from enable_shared_from_this and a method which returns a shared pointer by calling shared_from_this(). I would like to in that method detect if the object is owned by a shared_ptr and if not throw. I tried something like this:

shared_ptr<T> getPointer() {
    shared_ptr<T> ptr(shared_from_this()));
        throw "Not owned by smart pointer"
    return ptr;

This doesn't work though because a bad weak pointer exception is thrown during the construction of ptr. Is there another way.

Looking at the interface in the standard, I can't see anything which would do a decent test. Of course, you can always hack around the problem:

std::shared_ptr<T> getPointer() {
    try {
        return this->shared_from_this());
    catch (std::bad_weak_ptr const&) {
        throw std::runtime_error("not owned by smart pointer");

Of course, you could as well just not catch the std::bad_weak_ptr exception and have the original exception escape the function.

BTW, when throwing an exceptin it is trongly advised to throw an exception derived from std::exception. If you ever got an exception you know nothing you'll curse the guy who created it because it isn't always easy to get hold of that exception to find out what it is about (although debuggers can help, if necessary by setting a break point into the internal function throwing the exception). It is much easier to just write the result of what().