删除和删除[]相同的Visual C ++? [英] delete and delete [] the same in Visual C++?

查看:129
本文介绍了删除和删除[]相同的Visual C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我应该使用 new [] 后使用 delete [] code> auto_ptr 与新的[] 是不是一个好主意。



<然而,在调试 delete [] (使用Visual Studio 2005),我注意到调用进入一个函数,看起来像这样:

  void operator delete [](void * p)
{
RTCCALLBACK(_RTC_Free_hook,(p,0))
operator delete(p);
}

这是否意味着 [] 语法在Visual C ++上丢失了?如果是,为什么?

解决方案

请考虑这个代码:

  class DeleteMe 
{
public:
〜DeleteMe()
{
std: :cout< 感谢伙伴,我走了!\\\
;
}
};

int main()
{
DeleteMe * arr = new DeleteMe [5];
delete arr;
return 0;
}

如果你在VS2005中运行,它会打印:

感谢mate,我走了!

如果你改变 main 以正确遵守C ++标准:

  int main()
{
DeleteMe * arr = new DeleteMe [5];
delete [] arr;
return 0;
}

它将打印:

感谢伙伴,我走了! 
感谢mate,我走了!
感谢mate,我走了!
感谢mate,我走了!
感谢伙伴,我走了!

不要自己拍脚。 VS2005会做正确的事情,如果你不匹配不同的味道新/删除。



操作符$ operator delete (和它们不同的口味),基本上调用ctors和dtors是在幕后添加的。这个魔法取决于那些小括号[],所以不要失去它们,否则你会失去魔法。


I know that I am supposed to use delete [] after I use new [], so using auto_ptr with new [] is not such a bright idea.

However, while debugging delete [] (using Visual Studio 2005), I noticed that the call went into a function that looked like this:

void operator delete[]( void * p )
{
    RTCCALLBACK(_RTC_Free_hook, (p, 0))
    operator delete(p);
}

Does this mean, the [] syntax is lost on Visual C++? If so, why? Is it to relieve the developer from the burden of remembering the right syntax?

解决方案

Consider this code:

class DeleteMe
{
public:
  ~DeleteMe()
  {
    std::cout << "Thanks mate, I'm gone!\n";
  }
};

int main()
{
  DeleteMe *arr = new DeleteMe[5];
  delete arr;
  return 0;
}

If you run that in VS2005 it will print:

Thanks mate, I'm gone!

If you change main() to correctly adhere to the C++ standard:

int main()
{
  DeleteMe *arr = new DeleteMe[5];
  delete[] arr;
  return 0;
}

It will print:

Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!
Thanks mate, I'm gone!

Don't shoot yourself in the foot. VS2005 will NOT do the correct thing if you mismatch different flavors of new/delete. Neither will any other C++ standard conformant compiler.

There's some compiler magic going on around operator new and operator delete (and their different flavors), basically the call to the ctors and dtors are added behind the scenes. This magic depends on those small brackets [], so don't lose them or you'll lose the magic.

这篇关于删除和删除[]相同的Visual C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆