详解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既可能分配在栈上面也可能分配在堆上面

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值