简体   繁体   English

C ++'new'运算符 - 使用模式?

[英]C++ 'new' operator - Modes of use?

I recently ran into an unusual use of the new operator to re-initialise a C++ class, the code is as follows: 我最近遇到了一个不寻常的使用new运算符来重新初始化一个C ++类,代码如下:

#include <iostream>
struct Test { Test() { std::cout<<"Test Ctor\n"; }  };
int main()
{
  Test t ;
  new (&t) Test;
  return 0 ;
}

If this code is run, the Test ctor is called twice. 如果运行此代码,则会调用Test ctor两次。 In this case it appears that the 'new' operator is using the pointer to the object as the source of the memory rather than allocating new memory, valgrind comfirms no memory leaks. 在这种情况下,似乎'new'运算符使用指向对象的指针作为内存源而不是分配新内存,valgrind确认没有内存泄漏。

Can someone shed some light on this use of the 'new' operator? 有人能否对“新”运算符的使用有所了解?

This operator is called placement new. 此运算符称为placement new。 It runs the constructor of the object at the given addresss without prior memory allocation. 它在给定地址处运行对象的构造函数,而无需事先分配内存。 It could be used when allocating a large array first, then constructing many object on it, for instance. 例如,它可以在首先分配大型数组,然后在其上构建许多对象时使用。

It's called "placement new" and is usually used to construct an object in a specific memory location rather than the default returned by malloc . 它被称为“placement new”,通常用于构造特定内存位置的对象,而不是malloc返回的默认值。

It's not supposed to be used this way (double construction) and the standard doesn't say what the behavior of using it this way will be. 它不应该以这种方式使用(双重构造),并且标准没有说明以这种方式使用它的行为是什么。

That said, at least in the past. 那说,至少在过去。 the global iostreams used to rely on this double construction. 全球的iostream曾经依赖于这种双重结构。 (But that still doesn't make it a good idea.) (但这仍然不是一个好主意。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM