C++ 中的 placement new 操作

来源:互联网 发布:买家怎么修改淘宝评价 编辑:程序博客网 时间:2024/05/17 01:03

function
<new>

operator new

  • C++98
  • C++11

throwing (1)
void* operator new (std::size_t size);
nothrow (2)
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;
placement (3)
void* operator new (std::size_t size, void* ptr) noexcept;
Allocate storage space
Default allocation functions (single-object form).

(1) throwing allocation
Allocates size bytes of storage, suitably aligned to represent any object of that size, and returns a non-null pointer to the first byte of this block.
On failure, it throws a bad_alloc exception.
(2) nothrow allocation
Same as above (1), except that on failure it returns a null pointer instead of throwing an exception.
  • C++98
  • C++11

The default definition allocates memory by calling the the first version:::operator new (size).
If replaced, both the first and second versions shall return pointers with identical properties.
(3) placement
Simply returns ptr (no storage is allocated).
Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor).

The default allocation and deallocation functions are special components of the standard library; They have the following unique properties:
  • Global: All three versions of operator new are declared in the global namespace, not within thestd namespace.
  • Implicit: The allocating versions ((1) and (2)) areimplicitly declared in every translation unit of a C++ program, no matter whether header<new> is included or not.
  • Replaceable: The allocating versions ((1) and (2)) are alsoreplaceable: A program may provide its own definition that replaces the one provided by default to produce the result described above, or can overload it for specific types.

If set_new_handler has been used to define anew_handler function, thisnew-handler function is called by the default definitions of the allocating versions ((1) and(2)) if they fail to allocate the requested storage.

operator new can be called explicitly as a regular function, but in C++,new is an operator with a very specific behavior: An expression with thenew operator, first calls function operator new (i.e., this function) with the size of its type specifier as first argument, and if this is successful, it then automatically initializes or constructs the object (if needed). Finally, the expression evaluates as a pointer to the appropriate type.

Parameters

size
Size in bytes of the requested memory block.
This is the size of the type specifier in the new-expression when called automatically by such an expression.
If this argument is zero, the function still returns a distinct non-null pointer on success (although dereferencing this pointer leads toundefined behavior).
size_t is an integral type.
nothrow_value
The constant nothrow.
This parameter is only used to distinguish it from the first version with an overloaded version. When thenothrow constant is passed as second parameter tooperator new, operator new returns a null-pointer on failure instead of throwing abad_alloc exception.
nothrow_t is the type of constantnothrow.
ptr
A pointer to an already-allocated memory block of the proper size.
If called by a new-expression, the object is initialized (or constructed) at this location.

Return value

For the first and second versions, a pointer to the newly allocated storage space.
For the third version, ptr is returned.

Example

1234567891011121314151617181920212223242526272829303132333435363738
// operator new example#include <iostream>     // std::cout#include <new>          // ::operator newstruct MyClass {  int data[100];  MyClass() {std::cout << "constructed [" << this << "]\n";}};int main () {  std::cout << "1: ";  MyClass * p1 = new MyClass;      // allocates memory by calling: operator new (sizeof(MyClass))      // and then constructs an object at the newly allocated space  std::cout << "2: ";  MyClass * p2 = new (std::nothrow) MyClass;      // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)      // and then constructs an object at the newly allocated space  std::cout << "3: ";  new (p2) MyClass;      // does not allocate memory -- calls: operator new (sizeof(MyClass),p2)      // but constructs an object at p2  // Notice though that calling this function directly does not construct an object:  std::cout << "4: ";  MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));      // allocates memory by calling: operator new (sizeof(MyClass))      // but does not call MyClass's constructor  delete p1;  delete p2;  delete p3;  return 0;}



Possible output:
1: constructed [0x8f0f70]2: constructed [0x8f23a8]3: constructed [0x8f23a8]4: 

Data races

Modifies the storage referenced by the returned value.
Calls to allocation and deallocation functions that reuse the same unit of storage shall occur in a single total order where each deallocation happens entirely before the next allocation.
This shall also apply to the observable behavior of custom replacements for this function.

Exception safety

The first version (1) throws bad_alloc if it fails to allocate storage.
Otherwise, it throws no exceptions (no-throw guarantee).


new placement
你可以简单的理解为C中的realloc,就是在已有空间的基础上,重新分配一个空间,可以不破坏原来数据,也可以把数据全部用新值覆盖

一下是我搜集的一些笔记
如果你想在预分配的内存上创建对象,用缺省的new操作符是行不通的。要解决这个问题,你可以用placement new构造。它允许你构造一个新对象到预分配的内存上:


<span style="font-size:14px;">// buffer 是一个void指针 (void *)// 用方括号[] 括起来的部分是可选的[CYourClass * pValue = ] new( buffer) CYourClass[( parameters)];下面是一些例子:#include <newclass CTest{ public:    CTest(){}    CTest( int){}/* 代码*/};int main(int argc, char* argv[]){// 由于这个例子的目的,我们不考虑内存对齐问题    char strBuff[ sizeof( CTest) * 10 + 100];    CTest * pBuffer = ( CTest *)strBuff;// 缺省构造    CTest * pFirst = new(pBuffer) CTest;// 缺省构造    CTest * pSecond = new(pBuffer + 1) CTest;// 带参数的构造;// 不理会的指针    new(pBuffer + 2) CTest( 5);// 带参数的构造    CTest * pFourth = new( pBuffer + 3) CTest( 10);// 缺省构造    CTest * pFifth = new(pBuffer + 4) CTest();// 构造多个元素(缺省构造)    CTest * pMultipleElements = new(pBuffer + 5) CTest[ 5];    return 0;}</span>



当你有自己的内存缓冲区或者在你实现自己的内存分配策略的时候,placement new会很有用。事实上在STL中广泛使用了placement new来给容器分配内存;每个容器类都有一个模版参数说明了构造/析构对象时所用的分配器(allocator)。

在使用placement new的时候,你要记住以下几点:

加上头文件#include <new 你可以用placement new构造一个数组中的元素。 要析构一个用placement new分配的对象,你应该手工调用析构函数(并不存在一个“placement delete”)。它的语法如下:

pFirst-~CTest();

pSecond-~CTest();

//. . . 等等


placement new是重载operator new的一个标准、全局的版本,它不能被自定义的版本代替(不像普通的operator new和operator delete能够被替换成用户自定义的版本)。

它的原型如下:

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

 

首先我们区分下几个容易混淆的关键词:new、operator new、placement new

new和delete操作符我们应该都用过,它们是对堆中的内存进行申请和释放,而这两个都是不能被重载的。要实现不同的内存分配行为,需要重载operator new,而不是new和delete。

 

看如下代码:

class MyClass {…};

MyClass * p=new MyClass;

这里的new实际上是执行如下3个过程:

1调用operator new分配内存;

2调用构造函数生成类对象;

3返回相应指针。

operator new就像operator+一样,是可以重载的,但是不能在全局对原型为void operator new(size_t size)这个原型进行重载,一般只能在类中进行重载。如果类中没有重载operator new,那么调用的就是全局的::operator new来完成堆的分配。同理,operator new[]、operator delete、operator delete[]也是可以重载的,一般你重载了其中一个,那么最好把其余三个都重载一遍。

placement new是operator new的一个重载版本,只是我们很少用到它。如果你想在已经分配的内存中创建一个对象,使用new是不行的。也就是说placement new允许你在一个已经分配好的内存中(栈或堆中)构造一个新的对象。原型中void*p实际上就是指向一个已经分配好的内存缓冲区的的首地址。

我们知道使用new操作符分配内存需要在堆中查找足够大的剩余空间,这个操作速度是很慢的,而且有可能出现无法分配内存的异常(空间不够)。placement new就可以解决这个问题。我们构造对象都是在一个预先准备好了的内存缓冲区中进行,不需要查找内存,内存分配的时间是常数;而且不会出现在程序运行中途出现内存不足的异常。所以,placement new非常适合那些对时间要求比较高,长时间运行不希望被打断的应用程序。

 

使用方法如下:

1. 缓冲区提前分配

可以使用堆的空间,也可以使用栈的空间,所以分配方式有如下两种:

class MyClass {…};
char *buf=new char[N*sizeof(MyClass)+ sizeof(int) ] ;
或者char buf[N*sizeof(MyClass)+ sizeof(int) ];

2. 对象的构造

MyClass * pClass=new(buf) MyClass;

3. 对象的销毁

一旦这个对象使用完毕,你必须显式的调用类的析构函数进行销毁对象。但此时内存空间不会被释放,以便其他的对象的构造。

pClass->~MyClass();

4. 内存的释放

如果缓冲区在堆中,那么调用delete[] buf;进行内存的释放;如果在栈中,那么在其作用域内有效,跳出作用域,内存自动释放。

 

注意:

1)        在C++标准中,对于placement operator new []有如下的说明: placement operator new[] needs implementation-defined amount of additional storage to save a size of array. 所以我们必须申请比原始对象大小多出sizeof(int)个字节来存放对象的个数,或者说数组的大小。

2)        使用方法第二步中的new才是placement new,其实是没有申请内存的,只是调用了构造函数,返回一个指向已经分配好的内存的一个指针,所以对象销毁的时候不需要调用delete释放空间,但必须调用析构函数销毁对象。

-----------------------------------------------------------------------------------------------------------------

显式调用构造函数和析构函数

今天跟同事聊天,他说到STL源码有用到显示调用析构函数。试一了一下。果然能行。

 

 

结果:

Constructors

Destructors        //这个是显示调用的析构函数

Destructors        // 这个是delete调用的析构函数

 

这有什么用? 

有时候,在对象的生命周期结束前,想先结束这个对象的时候就会派上用场了。

 

由此想到的: 

因为我知道。

new的时候,其实做了两件事,一是:调用malloc分配所需内存,二是:调用构造函数。

delete的时候,也是做了两件事,一是:调用析造函数,二是:调用free释放内存。

 

所以推测构造函数也是可以显式调用的。做了个实现。

 

int _tmain(int argc, _TCHAR* argv[]){ MyClass* pMyClass = (MyClass*)malloc(sizeof(MyClass)); pMyClass->MyClass(); //}

 

 

编译pMyClass->MyClass()出错:

error C2273: 'function-style cast' : illegal as right side of '->'operator

天啊,它以为MyClass是这个类型。

 

解决办法有两个:

 

第一:pMyClass->MyClass::MyClass();第二:new(pMyClass)MyClass();

 

 

第二种用法涉及C++ placement new 的用法 。

placement new的作用就是:创建对象(调用该类的构造函数)但是不分配内存,而是在已有的内存块上面创建对象。用于需要反复创建并删除的对象上,可以降低分配释放内存的性能消耗。请查阅placement new相关资料。

显示调用构造函数有什么用? 

有时候,你可能由于效率考虑要用到malloc去给类对象分配内存,因为malloc是不调用构造函数的,所以这个时候会派上用场了。

 

另外下面也是可以的,虽然内置类型没有构造函数。

 

int* i = (int*)malloc(sizeof(int));new (i) int();

 

感觉这些奇奇怪怪的用法最好在写代码库时,为了达到某个目时去使用,不推荐应用开发时使用。

#include <iostream>usingnamespace std;class MyClass{public: MyClass() { cout <<"Constructors"<< endl; } ~MyClass() { cout <<"Destructors"<< endl; }};int _tmain(int argc, _TCHAR* argv[]){ MyClass* pMyClass =new MyClass; pMyClass->~MyClass(); delete pMyClass;}

 

0 0
原创粉丝点击