类方法读取同一变量 C++ 的不同值 [英] Class methods read different values of the same variable C++
问题描述
我的班级有一个用户定义类型的变量.我在类的一个方法中设置了这个变量.当我尝试从同一个类的另一个方法中获取该变量时,该值始终为 0,尽管该变量在其他任何地方都没有更改.
My class has a variable of a user-defined type. I set this variable in one method of the class. When I try to get this variable from another method of the same class, the value is always 0, although the variable has not been changed anywhere else.
我真的不明白为什么会这样!以下是我的代码示例:
I really don't understand why this happens! Follwoing is a sample of my code:
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
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
}
推荐答案
我发现这段代码有两个问题.
I see two problems with this code.
首先,std::bind
复制(或移动)它的所有参数.因此,从 bind
返回的函子值包含另一个从 myclass
对象复制构造的 MyClass
对象,并且对该函子的调用只会改变内部 MyClass
,而不是 myclass
.
First, std::bind
does a copy (or move) of all its arguments. So the functor value returned from bind
contains another MyClass
object which was copy-constructed from the myclass
object, and calls to that functor will only change the internal MyClass
, not myclass
.
您可以使用引用包装器来指定使用相同的 MyClass
对象:
You could use a reference-wrapper to specify using the same MyClass
object:
timerStart(std::bind(&MyClass::statusReceive, std::ref(myclass)), 10);
或者直接切换到 lambda 来调用 myclass
上的成员函数:
or just switch to a lambda to call the member function on myclass
directly:
timerStart([](){ myclass.statusReceive(); }, 10);
其次,您正在一个线程中修改 myclass.currentMode
对象并在另一个线程中读取它,而这两个操作之间没有任何同步.这是一种数据竞争和未定义的行为.
Second, you are modifying the myclass.currentMode
object in one thread and reading it in another without any synchronization between the two operations. This is a data race and undefined behavior.
这篇关于类方法读取同一变量 C++ 的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!