c++ - 删除 pointers-to-const 的行为在过去是否发生了变化?

标签 c++ visual-studio visual-c++ constants delete-operator

我从 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
   }

在该页面上,Microsoft 声称不允许删除指向 const 的指针,这对我来说似乎合乎逻辑。您不希望您提供指向 const 的指针的函数删除您背后的实例。

奇怪,问题 Deleting a pointer to const (T const*)表明它是允许的,甚至是有道理的。

事实上,如果我使用 Visual Studio 2010 从 MSDN 页面编译代码,它会正确编译(甚至在使用/W4 编译时没有警告)。

过去 C++ 标准中关于删除指向常量的指针的行为是否发生了变化?或者这是在 Visual Studio 中更改的吗?

最佳答案

您确实可以删除指向const的指针。

如果 Visual C++ 对符合标准的程序另有说明,则这是一个编译器错误,应该报告。

但是,您的(或 Microsoft 的?)程序不是标准的 C++,因为您的 main 的结果类型为 void

您链接到的知识库文章说“定义中不应允许删除指向常量的指针(ARM 第 5.3.4 节)”,虽然它是错误的,但它提供的引用是正确的。 ARM 第 5.3.4 节说“无法删除指向常量的指针”。然而,ARM 是在 1990 年发布的......

大约十年后,即 1998 年,C++ 实现了标准化,在标准 C++ 中,您可以删除指向 const 的指针。这在规范性文本中没有规定;它是通过省略限制来指定的。但是,C++98 标准 §5.3.5/2 有以下非规范性说明:

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.

我们现在再次标准化十多年,ARM 20 多年。

您使用的是哪个版本的 Visual C++?

干杯,

关于c++ - 删除 pointers-to-const 的行为在过去是否发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4826768/

相关文章:

c++ - 在 CEF 客户端中拖动时的图像预览

c++ - 如何向下转换 RefPtr

c++ - 如何强制库使用自定义 std::allocator?

c++ - 使用命名空间的多重定义错误

c++ - 高分辨率显示器导致MFC中View文字模糊

c++ - 为什么 sizeof 给我这个结果?

c++ - Visual Studio 2012 - C MariaDB 客户端 - 错误 LNK2019 : unresolved external symbol _mysql_init@4

c++ - 只有逐步调试,代码才能正常运行

visual-studio - Visual Studio/TFVC - checkin / checkout

c++ - 编译器忽略的函数模板特化