我有一个 int 的包装器类,名为 intWrapper
,还有一个将两个数字相加的函数 addN
,定义如下:
intWrapper* addN(intWrapper *first, intWrapper *second)
{
intWrapper c;
c.setData(first->getData() + second->getData());
return &c;
}
然后,在 main() 函数中我这样做:
intWrapper first(20), second(40);
intWrapper* t = addN(&first, &second);
cout << (*t).getData() << endl;
在 Dev-c++(MingW32) 中,这按预期执行,并将打印值 60
,但在 Visual C++ 中,我得到值 -858993460
。
但是,如果我使用 new 关键字在 addN 函数内创建一个新对象,它也会在 Visual C++ 中输出 60
。我很好奇为什么会这样。有什么想法吗?
完整代码在这里:
#include <iostream>
using namespace std;
template<typename T, T defaultValue>
class Wrapper
{
private: T n_;
public:
Wrapper(T n = defaultValue) : n_(n) {}
T getData()
{
return n_;
}
void setData(T n)
{
n_ = n;
}
};
typedef Wrapper<int, 47> intWrapper;
intWrapper* addN(intWrapper *first, intWrapper *second)
{
intWrapper c;
c.setData(first->getData() + second->getData());
return &c;
}
int main()
{
intWrapper p;
cout << p.getData() << endl;
intWrapper first(20), second(40);
intWrapper* t = addN(&first, &second);
cout << (*t).getData() << endl;
system("PAUSE");
return 1;
}
最佳答案
这是未定义的行为:您正在返回一个指向局部变量的指针,该变量将在函数返回时被破坏,这意味着返回值是一个悬空指针。
未定义的行为意味着任何事情都可能发生:它可能会崩溃,它可能看起来“正常工作”或可能无法正常工作。
当您使用 new
时,intWrapper
实例将存在于函数的范围之外并且不是未定义的行为并且将正常工作(对于 VC 和 MingW32)。请记住在不再需要时删除
返回的intWrapper*
。
关于c++ - 与 MingW 相比,Visual C++ 中的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9615619/