Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Was the behavior of deleting pointers-to-const changed in the past?

I got the following test code from http://support.microsoft.com/kb/131322:

const int * pi   = new int(1000);
const char * pch = new char(65);

void main(void)
   {
   delete  pi  ;// Error C2710:cannot delete a pointer to a const object
   delete  pch ;// Error C2710:cannot delete a pointer to a const object
   }

On that page Microsoft claims that deleting a pointer-to-const is not allowed, which seems logical to me. You don't want functions that you give a pointer-to-const to delete the instance behind your back.

Strange enough, question Deleting a pointer to const (T const*) indicates that it IS allowed, and it even makes sense.

And indeed, if I compile the code from the MSDN page with Visual Studio 2010, it compiles correctly (even no warnings when compiling with /W4).

Was the behavior regarding deletion of pointers-to-const changed in the past in the C++ standard? Or was this changed in Visual Studio?

like image 673
Patrick Avatar asked Jan 28 '11 09:01

Patrick


1 Answers

You can indeed delete a pointer-to-const.

If Visual C++ says otherwise for a standard-conforming program, then that's a compiler bug and should be reported.

Your (or Microsoft's?) program is not standard C++, however, since you have void result type for main.

The KB article you link to says "Deleting a pointer to a constant should not be allowed by definition (ARM section 5.3.4)", and although it's wrong, the reference it gives is correct. The ARM section 5.3.4 says "A pointer to constant cannot be deleted". However, the ARM was published in 1990...

C++ was standardized about ten years later, in 1998, and in standard C++ you can delete a pointer to const. This is not specified in the normative text; it's specified by omitting the restriction. However, the C++98 standard §5.3.5/2 has the following non-normative note:

a pointer to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the pointer expression before it is used as the operand of the delete-expression.

We are now over ten years after that standardization again, over 20 years after the ARM.

Which version of Visual C++ are you using?

Cheers & hth.,

like image 86
Cheers and hth. - Alf Avatar answered Sep 20 '22 03:09

Cheers and hth. - Alf