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 th开发者_运维问答at 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?
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.,
You are allowed to delete a pointer to const and Microsoft obviously had it wrong previously. The standard has never changed, as far as I'm aware.
No doubt someone with a copy will quote chapter and verse (and get a big rep for it).
main should return int though, not void.
Please also note that the Microsoft link itself says,
NOTE: Visual C++ .NET compiler does not demonstrate this issue in conformance to the changes made in the C++ ANSI Standards.
Interesting!
精彩评论