是一个很好的做法,通过指针到const释放内存 [英] Is it a good practice to free memory via a pointer-to-const
问题描述
有很多问题讨论C和C ++处理指针到const删除的细节,即 free()
不接受它们,而 delete
和 delete []
,并且const不会阻止对象破坏。
There are many questions discussing the details of C and C++ dealing with pointer-to-const deletion, namely that free()
does not accept them and that delete
and delete[]
do and that constness doesn't prevent object destruction.
我感兴趣的是你是否认为这是一个好的做法,而不是语言(C和C ++)允许的。
What I am interested on is whether you think it is a good practice to do so, not what the languages (C and C++) allow.
参数指针到const删除包括:
Arguments for pointer-to-const deletion include:
- Linus Torvalds'
kfree()
不像C的free()
,需要一个void const *
参数,因为他认为释放内存不会影响什么是指向。 -
free()
是在引入const关键字之前设计的。 - C ++的删除操作符允许删除const数据。
- Linus Torvalds'
kfree()
, unlike C'sfree()
, takes avoid const*
argument because he thinks that freeing the memory does not affect what is pointed to. free()
was designed before the introduction of the const keyword.- C++'s delete operators allow deletion of const data.
它的参数包括:
- 程序员不希望数据在传递指针到常量时被修改(或删除)。
- 这是大多数库和现有代码中常见的做法。 >
- Programmers do not expect data to be modified (or deleted) when they pass a pointer-to-const to it.
- Many think that pointer-to-const implies not getting ownership of the data (but not that non-const would imply getting ownership).
- This is the common practice seen in most libraries and existing code.
请在回答中说得很清楚,并且可能会涉及当局。我的意图是不要在这里开始投票。
Please argument well in your responses and possibly refer to authorities. My intention is not to start a poll here.
推荐答案
这里有一些相关的东西可能太长,
Well, here's some relevant stuff possibly too long to fit into a comment:
-
前一段时间以前通过指针到const释放内存的做法是被禁止的,参见 这个博士。
Some time ago the practice to free memory via a pointer-to-const was plain forbidden, see this dr. Dobb's article, the "Language Law" ( :)) part.
有两次有关 href =http://groups.google.ru/group/comp.lang.c++.moderated =nofollow> http://groups.google.ru/group/comp.lang.c++.moderated a>: 删除常量指针? , 为什么可以在const指针 (实际上处理有问题的情况,即指向const的指针)上调用operator delete。
There has twice been a relevant discussion on http://groups.google.ru/group/comp.lang.c++.moderated: "Delete a const pointer?", "Why can operator delete be called on a const pointer" (both actually deal with the case in question, i.e. pointer to const).
我自己的观点(因为你要求参数):任何给定上下文中的操作的可能性由(在文档中显式或隐式定义)或
My own point (since you are asking for arguments): possibility of the operation in question in any given context is defined by the (explicitly or implicitly defined in the documentation) contract of a class or a function, not by just the method signature or parameter types.
这篇关于是一个很好的做法,通过指针到const释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!