繁体   English   中英

C++ std::bind Function 作为 Class 变量中的参数存储

[英]C++ std::bind Function as Parameter Store in Class Variable

我有以下问题。 class A implements some routines that should be used on a dataset that is being processed in Class B. That means I'm calling the function start from class A . 我所做的应该保存在class A的变量m中。 到目前为止,一切都很好。 但是,当访问 class 变量m时,它在初始化时仍在 state 上。

准确地说:

#include <iostream>
#include <functional>

class A {
    public:
        int m;
        A() {
            m = 100;
        }
        void start(int value) {
            std::cout << "hello there!" << std::endl;
            m = value;
        }
};

class B {
    private:
        int m;
    public:
        void doSomething() {
            A a;
            doSomething2(std::bind(&A::start,a, std::placeholders::_1));
            
            // access variable m of instance a
            std::cout << a.m << std::endl;

        }
        template <typename Callable>
        void doSomething2(Callable f) {
            int val = 4444;
            f(val);
        }
};

main()
{
    B b;
    b.doSomething();
}

执行此操作时,我将获得100作为m的 output 。 我如何能够将start调用所做的更改存储在 class 变量中? 意思是,像本例一样存储值4444 谢谢

看起来您需要确保std::bind使用指向您创建的实际 class 实例的指针。 尝试将其更改为:

// notice I've got '&a' here instead of just 'a'
doSomething2(std::bind(&A::start, &a, std::placeholders::_1));

如果没有这个,我猜bind现在正在做的是复制a实例,然后修改该实例而不是更改它。

Bind 默认采用 arguments 的值,结果start()作用于 object a的副本。 您必须通过引用传递它:

doSomething2(std::bind(&A::start, std::ref(a), std::placeholders::_1));

可能的替代方法是改用 lambda 表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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