首页 > c/c++ > c++new的语义

c++new的语义

2015年8月16日 1,261 人阅读 发表评论 阅读评论

在使用c++过程中我们经常使用new来创建一个对象,比如:Test * p = new Test,实际上c++中有三个new,它们分别为:new operator,operator new,placement new我们平时调用的new是c++语言内置的new operator,不能被重载。

1、new operator

不能被重载,由三部分组成:

  • 为对象分配足够的内存(调用operator new)
  • 在分配的内存上构造对象(调用placement new)
  • 返回分配的内存地址

2、operator new

为对象分配内存,函数原型:void * operator new(size_t size);

3、placement new

在指定的空间(可能是堆,也可能是栈)上,构造对象(调用构造函数)

函数原型:void * operator new(size_t size, void * buf);

Demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;
 
class Test
{
public:
	Test()
	{
		cout << "call Test()" << endl;
	}
	~Test()
	{
		cout << "call ~Test()" << endl;
	}
 
	void * operator new(size_t size)
	{
		cout << "call self_def operator new" << endl;
		return ::operator new(size);                 //调用全局operator new
	}
 
	void * operator new(size_t size, void * buffer)
	{
		cout << "call self_def placement new" << endl;
		return buffer;
	}
};
 
int main()
{
	Test * p1 = new Test;          //调用new operator
	char buf[100];
	char * p = (char *)malloc(100);
	new(buf) Test;                 //在栈上构造对象
	new(p) Test;                   //在堆上构造对象
	return 0;
}
分类: c/c++ 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.