C++ 中的就地构造函数是什么?
C++ 中的就地构造函数是什么?
例如Datatype *x = new(y) Datatype();
What is an in-place constructor in C++?
e.g. Datatype *x = new(y) Datatype();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这称为放置新运算符。它允许您提供将分配数据的内存,而无需 new 运算符分配它。例如:
上面将为你分配内存。
上面将使用通过调用
malloc
分配的内存。new
将不再分配。但是,您并不局限于课程。您可以对通过调用new
分配的任何类型使用放置 new 运算符。Placement new 的一个“陷阱”是,您不应该释放使用
delete
关键字调用 Placement new 运算符分配的内存。您将通过直接调用析构函数来销毁该对象。手动调用析构函数后,内存就可以按预期释放。
This is called the placement new operator. It allows you to supply the memory the data will be allocated in without having the
new
operator allocate it. For example:The above will allocate memory for you.
The above will use the memory allocated by the call to
malloc
.new
will not allocate any more. You are not, however, limited to classes. You can use a placement new operator for any type you would allocate with a call tonew
.A 'gotcha' for placement new is that you should not release the memory allocated by a call to the placement new operator using the
delete
keyword. You will destroy the object by calling the destructor directly.After the destructor is manually called, the memory can then be freed as expected.
简而言之,您的代码在 y 指向的空间中构造了一个对象。 C++ 常见问题解答 最好地涵盖了长答案。
The short answer is that your code constructs an object in the space pointed to by
y
. The long answer is best covered by the C++ FAQ.这通常被称为“placement new”,C++ FAQ(在“析构函数”区域)对此进行了很好的讨论:
它允许您在原始内存中构造对象,这在某些特殊情况下很有用,例如当您可能想要为大量可能的对象分配一个数组,但想要根据需要构造然后,因为您通常可能不需要接近最大值的任何地方,或者因为您想要或者需要使用自定义内存分配器。
This is more commonly known as 'placement new' and is discussed pretty well by the C++ FAQ (in the 'Destructors' area):
It allows you to construct objects in raw memory, which can be useful in certain specialized situations, such as when you might want to allocate an array for a large number of possible objects, but want to construct then as needed because you often might not need anywhere near the maximum, or because you want or need to use a custom memory allocator.
我对此很生疏,但它允许您将对象写入已经分配的内存块。它还需要一个相反的删除语句来将其从内存中清除。
I'm rusty on this one but it allows you to write the object to a memory block you have already allocated. It also needs a reciprocal delete statement to clear it from memory.
如果您使用内存池,则需要使用就地构造函数来初始化对象,因为它们是从池中分配的。
If you use a memory pool, then you need to use the in place constructor to initialize your object as they are allocated from the pool.
这是一种无需分配内存即可调用构造函数的方法。您的 y 必须是指向新 Datatype 对象足够内存的指针。另外,不要调用
delete
,而是调用~DataType()
。It's a way to call a constructor without allocating memory. Your
y
has to be a pointer poniting to enough memory for a new Datatype object. Also, don't calldelete
, call~DataType()
.