Bryan Fok
Bryan Fok

Reputation: 3487

How to make std::function reference

How do I make a reference to the callable object? I would like to create a pub/sub with std::function. From the below code, have I made a copy of Test, or it was something else? Alternative suggestion also welcome.

using Callback = std::function<void ()>;

struct Test
{
    void operator()()
    {
        std::cout << a ;
    };

    int a;
};

struct Sub
{
void Subscribe(Callback callback)
{
    callback_ = callback;
}

void trigger()
{
     callback_();
}

Callback callback_;
};

int main() {

    Test a = {1};

    Sub sub;
    sub.Subscribe(a);
    a.a = 2;
    sub.trigger();

}

Upvotes: 0

Views: 130

Answers (1)

Dean Seo
Dean Seo

Reputation: 5703

Use std::ref as follows:

sub.Subscribe(std::ref(a));

or make a lambda function with a reference capture:

sub.Subscribe([&a](){ a(); });

Now that you're passing a reference instead, make sure &a is not dangling after it exits the local scope. (There can be many good ways to prevent that)

Upvotes: 3

Related Questions