简体   繁体   中英

use *this as std::shared_ptr

here is a "chess++" problem that I'm facing wright now with my nested class, although it may look like some joke, it's not a joke but real problem which I want to either solve or change the way to achieve the same thing in my project.

#include <map>
#include <memory>
#include <iostream>
#include <sigc++/signal.h>

class foo
{
public:
    struct bar;

    typedef sigc::signal<void, std::shared_ptr<bar>> a_signal;

    struct bar
    {
        bar()
        {
            some_signal.connect(sigc::mem_fun(*this, &foo::bar::func));
        }

        void notify()
        {
            some_signal.emit(this); // how to ??
        }

        void func(std::shared_ptr<foo::bar> ptr)
        {
            std::cout << "you haxor!" << std::endl;
            // use the pointer ptr->
        }

        a_signal some_signal;
    };

    std::map<int, std::shared_ptr<bar>> a_map;
};

int main()
{
    std::shared_ptr<foo::bar> a_foo_bar;
    foo foo_instance;

    foo_instance.a_map.insert(std::pair<int, std::shared_ptr<foo::bar>>(4, a_foo_bar));
    foo_instance.a_map.at(0)->notify();
    return 0;
}

What I want to do here is to emit a signal. the signal is declared as one that triggers a handler that takes a shared_ptr as an argument. the function notify() should convert *this into shared_ptr, how do I do that to make the above code run?

Derive from enable_shared_from_this :

struct bar : std::enable_shared_from_this<bar>

to get a member shared_from_this() :

some_signal.emit(shared_from_this());

As long as the current object is owned by at least one shared pointer, this will return a shared pointer, sharing ownership with that pointer. Note that, in your program, a_foo_bar is empty, so neither this nor the call to notify will work. Also beware that it won't work from the constructor or destructor, since the object is not owned by a shared pointer at that time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM