Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
类方法读取相同变量C++的不同值_C++_Oop - Fatal编程技术网

类方法读取相同变量C++的不同值

类方法读取相同变量C++的不同值,c++,oop,C++,Oop,我的类有一个用户定义类型的变量。我在类的一个方法中设置了这个变量。当我尝试从同一类的另一个方法获取此变量时,该值始终为0,尽管该变量在其他任何地方都没有更改 我真的不明白为什么会这样!以下是我的代码示例: myclass.h typedef enum { ACTIVE = 0, SLEEP = 1, FINISHED = 2, WAITING = 3, KILLED = 4 } Mode; class MyClas

我的类有一个用户定义类型的变量。我在类的一个方法中设置了这个变量。当我尝试从同一类的另一个方法获取此变量时,该值始终为0,尽管该变量在其他任何地方都没有更改

我真的不明白为什么会这样!以下是我的代码示例:

myclass.h

typedef enum {
    ACTIVE   =  0,  
    SLEEP    =  1,  
    FINISHED =  2,  
    WAITING  =  3,
    KILLED   =  4
} Mode;


class MyClass
{
    public:
      void statusReceive(void);
      Mode getCurrentMode(void);

    private:
      Mode currentMode;
};
myclass.cpp

#include "myclass.h"

void MyClass::statusReceive(void)
{
    currentMode = (Mode)interpretMsg(&msg);
    printf("current Mode = %d\n", this->currentMode); // prints 4
}

Mode MyClass::getCurrentMode(void)
{
    printf("current Mode = %d\n", this->currentMode);   // prints 0
    return this->currentMode;
}
main.cpp

#include "myclass.h"

MyClass myclass;

void timerStart(std::function<void(void)> func, unsigned int interval)
{
    std::thread([func, interval]()
            { 
            while (true)
            { 
            auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
            func();
            std::this_thread::sleep_until(x);
            }
            }).detach();
}

int main(void)
{
    timerStart(std::bind(&MyClass::statusReceive, myclass), 10);
    Mode x = myclass.getCurrentMode();
    printf("Current Mode = %d\n", x); // prints 0
}

我发现这个代码有两个问题

首先,std::bind复制或移动其所有参数。因此,从bind返回的functor值包含另一个MyClass对象,该对象是从MyClass对象复制构造的,对该functor的调用只会更改内部MyClass,而不会更改MyClass

您可以使用引用包装器指定使用相同的MyClass对象:

或者直接切换到lambda来调用myclass上的成员函数:

timerStart([](){ myclass.statusReceive(); }, 10);

其次,您在一个线程中修改myclass.currentMode对象,并在另一个线程中读取它,而这两个操作之间没有任何同步。这是一种数据竞争和未定义的行为。

您的意思是模式x=myclass.getValue;什么是模式?这个代码是正确的,我们知道它不是你真正失败的代码。我们需要看到它正在运行,除了模式值之外,您还可以打印它。你有两个物体。在绑定、函数、lambda和线程之外,有人创建了一个额外副本。do printfcurrent Mode=%d adr=%p\n,this->currentMode,this;除了使用myclass而不是This之外,其他内容都是一样的。谢谢@aschepler的回答。不幸的是,在星期一早上之前,我无法进入我在大学的工作站。我一尝试你的解决方案就会给你反馈。再次感谢
timerStart([](){ myclass.statusReceive(); }, 10);