开发者

Try-Catch and Delete[] issue

I'm having a bit of a problem with a try-catch situation, here goes the code (it's pretty simple):

struct Something
{
  int A, B, C;
  Something()
  {
    A = B = C = 0;
  }
  ~Something()
  {
    cout << "Destructor " << endl;
  }
};

int main()
{
  Something * s = new Something;

  //Something * s = new Something[5];

  try
  {
    delete[] s;
  }
  catch(exception& e)
  {
    delete s;
  }
  return 0;
}

What I intend to do is to first try to delete the pointer as an array, if it fails, make a simple delete.

So, when I first try it with an array of 'Something's (as in the commented line), itr worked perfectly. But when I try it 开发者_高级运维as it is now, I get a horrible error.

Any ideas?


What your trying to do is neither legal C++ nor does it make sense.

An allocation with new must be followed by a deletion with delete, and an allocation with new[] by delete[]; this must happen precisely like that, and everything else is undefined behaviour.

You cannot "try and see if you wrote correct code". Exceptions signal exceptional runtime behaviour, but your error is a static, compile-time error that cannot be handled, but must be fixed.

However, there should never be a point in your code where you don't know what a given pointer means! Since the language is statically typed, you should in principle always have knowledge of the involved types. And if you want to pass objects around (possibly polymorphically), then anything that requires dynamic allocation should be wrapped in its own manager class (like shared_ptr or unique_ptr).


Deleting a pointer as an array (or vica versa) is incorrect and undefined. It won't throw an exception.

You should consider RAII. For example, create a class which contains the pointer as a member. The constructor allocates the memory, and the destructor deletes it.

Then you've got a few options:

(1) Have two constructors, one for a single item and one for an array. Place a boolean in the class that holds whether the pointer points to one item or an array, and check this on destruction and call the appropriate delete function.

(2) Make your class a template class that takes a boolean template parameter and resolve this choice at compile time.


You completely misunderstand the semantics of try/catch. They don't catch errors, they catch exceptions. You can only rely on an exception being created if you throw it yourself or do something that's guaranteed to throw an exception. Calling delete on a pointer allocated with new[] is not guaranteed to throw an exception, in fact, it's not guaranteed to do anything specific.


So my c++ skills are rusty but delete[] is called where you've called new[]. You haven't called new[] in your example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜