C++ 删除空指针是否安全?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/941832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:05:09  来源:igfitidea点击:

Is it safe to delete a void pointer?

c++memory-managementcastingvoid-pointers

提问by An???drew

Suppose I have the following code:

假设我有以下代码:

void* my_alloc (size_t size)
{
   return new char [size];
}

void my_free (void* ptr)
{
   delete [] ptr;
}

Is this safe? Or must ptrbe cast to char*prior to deletion?

这安全吗?或者必须ptr被强制转换为char*之前删除?

采纳答案by Christopher

It depends on "safe." It will usually work because information is stored along with the pointer about the allocation itself, so the deallocator can return it to the right place. In this sense it is "safe" as long as your allocator uses internal boundary tags. (Many do.)

这取决于“安全”。它通常会起作用,因为信息与有关分配本身的指针一起存储,因此解除分配器可以将其返回到正确的位置。从这个意义上说,只要您的分配器使用内部边界标记,它就是“安全的”。(许多人这样做。)

However, as mentioned in other answers, deleting a void pointer will not call destructors, which can be a problem. In that sense, it is not "safe."

但是,正如其他答案中提到的,删除 void 指针不会调用析构函数,这可能是一个问题。从这个意义上说,它并不“安全”。

There is no good reason to do what you are doing the way you are doing it. If you want to write your own deallocation functions, you can use function templates to generate functions with the correct type. A good reason to do that is to generate pool allocators, which can be extremely efficient for specific types.

没有充分的理由去做你正在做的事情。如果要编写自己的解除分配函数,可以使用函数模板生成具有正确类型的函数。这样做的一个很好的理由是生成池分配器,这对于特定类型非常有效。

As mentioned in other answers, this is undefined behaviorin C++. In general it is good to avoid undefined behavior, although the topic itself is complex and filled with conflicting opinions.

正如其他答案中提到的,这是C++ 中未定义的行为。一般来说,避免未定义的行为是好的,尽管主题本身很复杂,而且充满了相互矛盾的意见。

回答by

Deleting via a void pointer is undefined by the C++ Standard - see section 5.3.5/3:

C++ 标准未定义通过 void 指针删除 - 请参阅第 5.3.5/3 节:

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.

在第一种选择(删除对象)中,如果操作数的静态类型与其动态类型不同,则静态类型应为操作数动态类型的基类,静态类型应具有虚拟析构函数或行为未定义. 在第二种选择(删除数组)中,如果要删除的对象的动态类型与其静态类型不同,则行为未定义。

And its footnote:

以及它的脚注:

This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void

这意味着不能使用 void* 类型的指针删除对象,因为没有 void 类型的对象

.

.

回答by Brian R. Bondy

It's not a good idea and not something you would do in C++. You are losing your type info for no reason.

这不是一个好主意,也不是您在 C++ 中会做的事情。您无缘无故丢失了类型信息。

Your destructor won't be called on the objects in your array that you are deleting when you call it for non primitive types.

当您为非基本类型调用析构函数时,不会在要删除的数组中的对象上调用析构函数。

You should instead override new/delete.

您应该改写新/删除。

Deleting the void* will probably free your memory correctly by chance, but it's wrong because the results are undefined.

删除 void* 可能会偶然正确释放您的内存,但这是错误的,因为结果未定义。

If for some reason unknown to me you need to store your pointer in a void* then free it, you should use malloc and free.

如果由于某种原因我不知道您需要将指针存储在 void* 中然后释放它,您应该使用 malloc 和 free。

回答by JaredPar

Deleting a void pointer is dangerous because destructors will not be called on the value it actually points to. This can result in memory / resource leaks in your application.

删除 void 指针是危险的,因为不会在它实际指向的值上调用析构函数。这可能会导致应用程序中的内存/资源泄漏。

回答by Kerrek SB

The question makes no sense. Your confusion may be partly due to the sloppy language people often use with delete:

这个问题没有意义。您的困惑可能部分是由于人们经常使用的草率语言delete

You use deleteto destroy an objectthat was dynamically allocated. Do do so, you form a delete expressionwith a pointer to that object. You never "delete a pointer". What you really do is "delete an object which is identified by its address".

delete用来销毁动态分配的对象。这样做,您会形成一个带有指向该对象指针删除表达式。你永远不会“删除一个指针”。您真正要做的是“删除由其地址标识的对象”。

Now we see why the question makes no sense: A void pointer isn't the "address of an object". It's just an address, without any semantics. It mayhave come from the address of an actual object, but that information is lost, because it was encoded in the typeof the original pointer. The only way to restore an object pointer is to cast the void pointer back to an object pointer (which requires the author to know what the pointer means). voiditself is an incomplete type and thus never the type of an object, and a void pointer can never be used to identify an object. (Objects are identified jointly by their type and their address.)

现在我们明白为什么这个问题没有意义了:空指针不是“对象的地址”。它只是一个地址,没有任何语义。它可能来自实际对象的地址,但该信息丢失了,因为它以原始指针的类型编码。恢复对象指针的唯一方法是将void指针强制转换回对象指针(这需要作者知道指针的含义)。void本身是不完整的类型,因此永远不会是对象的类型,并且永远不能使用 void 指针来标识对象。(对象由它们的类型和它们的地址共同标识。)

回答by bk1e

If you really must do this, why not cut out the middle man (the newand deleteoperators) and call the global operator newand operator deletedirectly? (Of course, if you're trying to instrument the newand deleteoperators, you actually ought to reimplement operator newand operator delete.)

如果你真的必须这样做,为什么不去掉中间人(newdelete操作符)operator newoperator delete直接调用全局和?(当然,如果您尝试检测newanddelete运算符,您实际上应该重新实现operator newand operator delete。)

void* my_alloc (size_t size)
{
   return ::operator new(size);
}

void my_free (void* ptr)
{
   ::operator delete(ptr);
}

Note that unlike malloc(), operator newthrows std::bad_allocon failure (or calls the new_handlerif one is registered).

请注意,与malloc(), operator newthrowsstd::bad_alloc失败(或调用new_handlerif 已注册)。

回答by young

If you want to use void*, why don't you use just malloc/free? new/delete is more than just memory managing. Basically, new/delete calls a constructor/destructor and there are more things going on. If you just use built-in types (like char*) and delete them through void*, it would work but still it's not recommended. The bottom line is use malloc/free if you want to use void*. Otherwise, you can use template functions for your convenience.

如果您想使用 void*,为什么不只使用 malloc/free?新建/删除不仅仅是内存管理。基本上,new/delete 调用构造函数/析构函数,并且还有更多事情要做。如果您只是使用内置类型(如 char*)并通过 void* 删除它们,它会起作用,但仍然不推荐。如果你想使用 void*,底线是使用 malloc/free。否则,您可以为方便起见使用模板函数。

template<typename T>
T* my_alloc (size_t size)
{
   return new T [size];
}

template<typename T>
void my_free (T* ptr)
{
   delete [] ptr;
}

int main(void)
{
    char* pChar = my_alloc<char>(10);
    my_free(pChar);
}

回答by young

Because char has no special destructor logic. THIS won't work.

因为 char 没有特殊的析构函数逻辑。这行不通。

class foo
{
   ~foo() { printf("huzza"); }
}

main()
{
   foo * myFoo = new foo();
   delete ((void*)foo);
}

The d'ctor won't get called.

d'ctor 不会被叫到。

回答by Paul Morie

A lot of people have already commented saying that no, it's not safe to delete a void pointer. I agree with that, but I also wanted to add that if you're working with void pointers in order to allocate contiguous arrays or something similar, that you can do this with newso that you'll be able to use deletesafely (with, ahem, a little of extra work). This is done by allocating a void pointer to the memory region (called an 'arena') and then supplying the pointer to the arena to new. See this section in the C++ FAQ. This is a common approach to implementing memory pools in C++.

很多人已经评论说不,删除空指针是不安全的。我同意这一点,但我还想补充一点,如果您正在使用 void 指针来分配连续数组或类似的东西,您可以这样做,new以便您可以delete安全地使用(使用,咳咳,一些额外的工作)。这是通过为内存区域(称为“arena”)分配一个空指针,然后将指向该arena 的指针提供给new 来完成的。请参阅C++ FAQ中的这一部分。这是在 C++ 中实现内存池的常用方法。

回答by Sanjaya R

If you just want a buffer, use malloc/free. If you must use new/delete, consider a trivial wrapper class:

如果您只想要一个缓冲区,请使用 malloc/free。如果您必须使用 new/delete,请考虑一个简单的包装类:

template<int size_ > struct size_buffer { 
  char data_[ size_]; 
  operator void*() { return (void*)&data_; }
};

typedef sized_buffer<100> OpaqueBuffer; // logical description of your sized buffer

OpaqueBuffer* ptr = new OpaqueBuffer();

delete ptr;