我遇到了一个奇怪的场景,我不明白为什么会这样。
我有一个带有简单 int
成员的对象。
类名.h文件:
private:
int m_variable;
public:
...
(constructor and the rest of the functions)
...
类名.cpp文件:
void className::function()
{
...
m_variable = pointerToOtherClass->getMaxDistOfAllMatrices(); //first call
int x = pointerToOtherClass->getMaxDistOfAllMatrices(); //second call
m_variable = x;
cout << m_variable << "," << x;
}
第一次调用和第二次调用的功能相同,即返回相同的值。
当我在第一个调用上设置断点并跳过调用时,我看到 m_variable
保持垃圾并且 x
保持 4(预期结果)。 m_variable = x;
行没有任何变化(x=4
,m_variable
仍然是垃圾)并且在 cout
之后它按预期打印 4,4
。
first call
这一行,是代码第一次遇到m_variable
。
我不明白为什么会这样,我是不是做错了什么?
最佳答案
您看到了优化工件。
将函数 getMaxDistOfAllMatrices()
的 first 结果存储到变量 m_variable
被省略,因为两行之后第一次调用第二次调用的结果函数再次存储到该变量(通过 x
)。
x
保存预期值,因为它稍后会在 cout
中使用。
请注意,调用的函数不会被省略(调用两次),因为它可能有副作用,但忽略第一个结果是有效的。
m_variable = ponterToOtherClass->getMaxDistOfAllMatrices(); //first call
跨过上面一行后,您可能会在 m_variable
中看到垃圾。
int x = ponterToOtherClass->getMaxDistOfAllMatrices(); //second call
m_variable = x;
跨过以上两行后,您会在两个变量中看到预期值。
关于c++ - 成员变量在赋值后保存垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30213145/