详解C++三种new的使用方法(在栈上用new生成对象)

new operator:

int *num = new int(123);

实际发生的是:

	void *temp = operator new(sizeof(int));
	new (temp) int(123);
	int *num = static_cast<int*>(temp);

operator new() :

void *CRTDECL operator new(size_t size) throw(std::bad_alloc)
{
	void *p;
	while((p = malloc(size))==0)
		if(_callnewh(size)==0)
		{
			static const std::bad::bad_alloc nomem;
			::std:: _Throw(nomen);
		}
		return(p);
}

placement new():

#include<iostream>
#include <type_traits>

using namespace std;

class A
{
	int myself;
};

void function() {
	printf("h \n");
}

int main()
{	
	A* t = (A*)malloc(sizeof(A));
	new(t) A();
	t->~A();
}

 也可写为如下分配格式

	A* t = (A*)malloc(sizeof(A));
	t = new A;
	t->~A();

使用placement new操作以后,既可以在栈上生成也可以在堆上面声明,malloc是在堆上面分配内存,所以使用placement new分配的内存分配在了堆上面

如果想分配在栈上面,可以写成下面的格式:

	A* t = (A*)alloca(sizeof(A));
	new(t) A();
	t->~A();

所以说new既可能分配在栈上面也可能分配在堆上面

猜你喜欢

转载自blog.csdn.net/qq_36653924/article/details/128820839