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

1 c++ mingw32 visual-c++

我有一个int的包装类,一个名为intWrapper,以及一个addN添加两个数字的函数,定义如下:

intWrapper* addN(intWrapper *first, intWrapper *second)
{
    intWrapper c;
    c.setData(first->getData() + second->getData());
    return &c;
}
Run Code Online (Sandbox Code Playgroud)

然后,在main()函数中我这样做:

intWrapper first(20), second(40);
intWrapper* t = addN(&first, &second);
cout << (*t).getData() << endl;
Run Code Online (Sandbox Code Playgroud)

在Dev-c ++(MingW32)中,它按预期执行,并将打印该值60,但在Visual C++中我得到了值-858993460.
但是,如果我使用new关键字在addN函数中创建一个新对象,它60也会在Visual C++中输出.我很感兴趣为什么会这样.有什么想法吗?
完整代码在这里:

#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;
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 7

这是未定义的行为:您正在返回一个指向局部变量的指针,该函数将在函数返回时被破坏,这意味着返回值是悬空指针.

未定义的行为意味着任何事情都可能发生:它可能会崩溃,它可能看起来"正常"工作或可能无法正常工作.

当您使用newintWrapper实例时,将存在超出函数范围并且不是未定义的行为并且将正常工作(对于VC和MingW32).记得不再需要时delete返回intWrapper*.

  • @ hero47如果这个答案是你问题的一个(或最好的)解决方案,那么[接受它](http://meta.stackexchange.com/q/5234/162011)将是正确的答案. (2认同)