标签:
new
和delete
的基本概念new
所隐含的三步内容
delete
所隐含的两步内容
//auto pi = new int; // built-in type 不完成初始化
auto pi = new int{}; // 系统会初始化 = 0
//auto = pc new complex<double>;
auto = pc new complex<double> {}; // 系统会调用初始化函数
array
和vector
的使用
class with array
的使用Code: https://github.com/weiweikong/Program_Practice/tree/master/160331.Geekband_Homework5
构造指针,从上至下一次创建
operator new/new[]
和operator delete/delete[]
的讨论operator new/ operator new[]
要求
*void
size_t
operator delete/ operator delete[] 要求
void
void*
基本例子
malloc
和free
的使用要小心
void* operator new(size_t size) {
if (void* mem = malloc(size) // 判断是否成功
return mem;
else
throw bad_alloc();
}
void operator delete(void* mem) noexcept{
if (mem)
free(mem)
}
new
和delete
Foo* pf = ::new Foo;
::delete pf;
new
和delete
的时机new
和delete
的效率会很高,对内存池的操作。placement operator new
delete
new
的使用和delete
要搭配
int* p1 = new int{99}
int* p2 = p2;
delete p1; // p2 doesn‘t point to a valid object
p1 = nullptr;
void sloppy()
{
int* p = new int[100];
// use *p
deletep[] p;
// other codes.
delete[] p; // prone to wrong
}
delete
之前跳出,导致内存泄漏
void f1() {
X* p = new X;
// ... use *p ...
delete p;
void f2() {
X x;
// ... use x
}
virtual
Base* p = new Child;
// ... use *p
delete p;
Base
需要有virtual dtor
,否则就会导致调用dtor
错误【C++】Geekband - 专题一:new和delete的整理
标签:
原文地址:http://www.cnblogs.com/kongww/p/5350308.html