c++ - 与 MingW 相比,Visual C++ 中的不同行为

标签 c++ visual-c++ mingw32

我有一个 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/

相关文章:

c++ - 如何合并(连接)2 个列表?

c++ - Microsoft Visual Studios 2012 无法打开 "python33.lib"

c++ - 安装MinGW时如何设置环境变量PATH(Windows 32位)

c - C 中的内联 ASM,使用 "-masm=intel": "undefined reference" 使用 MinGW/GCC 编译

c - Wininet 不向服务器发送 cookie

c++ - 检索对象的函数运算符的参数类型

c++ - 如何在 PostgreSQL 中创建插入、删除或更新命令的信号并在 C++ 中处理它们?

c++ - OpenGL 中的地形小 map ?

visual-c++ - 将所有警告视为错误,某些警告除外

visual-c++ - 如何判断一个 Visual Studio 项目文件是代表应用程序、DLL 还是静态库项目?