gpt4 book ai didi

c++ - 运算符删除函数的放置形式

转载 作者:可可西里 更新时间:2023-11-01 16:39:33 25 4
gpt4 key购买 nike

在他的新书中TC++PL4, Stroustrup 对 a once usual practice 的看法略有不同。 regarding user-controlled memory allocation and placement new ——或者,更具体地说,关于神秘的“位置 delete”。在书的宗派。 11.2.4,Stroustrup 写道:

The "placement delete" operators do nothing except possibly inform a garbage collector that the deleted pointer is no longer safely derived.

这意味着合理的编程实践将遵循 a call to placement delete 对析构函数的显式调用。 .

很公平。但是,有没有更好的语法来调用placement delete比晦涩难懂

::operator delete(p);

我问的原因是 Stroustrup 的教派。 11.2.4 没有提到这种奇怪的语法。事实上,Stroustrup 并没有详述此事;他根本没有提到语法。我隐约不喜欢 ::operator 的样子,它将命名空间解析问题插入到与命名空间无关的事情中。不存在更优雅的语法吗?

作为引用,这里是 Stroustrup 在更完整的上下文中的引述:

By default, operator new creates its object on the free store. What if we wanted the object allocated elsewhere?... We can place objects anywhere by providing an allocator function with extra arguments and then supplying such extra arguments when using new:

void* operator new(size_t, void* p) { return p; }

void buf = reinterpret_cast<void*>(0xF00F);
X* p2 = new(buf) X;

Because of this usage, the new(buf) X syntax for supplying extra arguments to operator new() is known as the placement syntax. Note that every operator new() takes a size as its first argument and that the size of the object allocated is implicitly supplied. The operator new() used by the new operator is chosen by the usual argument-matching rules; every operator new() has a size_t as its first argument.

The "placement" operator new() is the simplest such allocator. It is defined in the standard header <new>:

void* operator new (size_t, void* p) noexcept;
void* operator new[](size_t, void* p) noexcept;

void* operator delete (void* p, void*) noexcept; // if (p) make *p invalid
void* operator delete[](void* p, void*) noexcept;

The "placement delete" operators do nothing except possibly inform a garbage collector that the deleted pointer is no longer safely derived.

Stroustrup 然后继续讨论放置的使用 new与竞技场。他似乎没有提到安置 delete再次。

最佳答案

如果你不想使用::,你真的没有必要。事实上,您通常不应该(不想)。

您可以为 ::operator new::operator delete 提供替换(以及数组变体,尽管您永远不应该使用它们)。

但是,您也可以为类重载 operator newoperator delete(是的,您可以再次使用数组变体,但仍然不应该永远使用它们)。

使用 void *x =::operator new(some_size); 强制分配直接进入全局 operator new 而不是使用特定类(如果存在)。当然,通常情况下,如果存在类特定类(如果不存在则使用全局类)。这正是您使用 void *x = operator new(some_size);(即无范围解析运算符)所获得的结果。

一如既往,您需要确保您的newdelete匹配,所以您应该只使用::operator delete来当/如果您使用 ::operator new 分配内存时删除内存。大多数时候你不应该在任何一个上使用 ::

主要的异常(exception)是当/如果您实际上正在为某个类编写 operator newoperator delete。这些通常会调用 ::operator new 来获取一大块内存,然后将其分成对象大小的 block 。要分配那么大的内存块,它通常(总是?)必须显式指定 ::operator new,否则它最终会调用自己来分配它。显然,如果在分配数据的时候指定了::operator new,那么也需要指定::operator delete来匹配。

关于c++ - 运算符删除函数的放置形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com