"operator new" 和"new operator "
2009-03-05 13:53
399 查看
内存管理(operator new与new operator)
今天看了大名鼎鼎的Scott Meyers所著的〈effective c++〉和〈more effective c++〉中关于new和delete的介绍,惊讶不已,大师果然名不虚传,研究的如此细致、透彻,让我这个菜鸟受益非浅(窃喜,呵呵)。
在C++中new operator与operator new非一回事也,new operator(即所谓的new expression)乃语言内建,咱们是没法改变其行为的,当你写string *ps = new string("Hands up!")时,你所使用的new是所谓的new operator,它其实干了两件事:一、分配足够的内存(实际大小是大于所创建的对象大小)二、调用对象构造函数,new operator永远干这两件事。上面的那段代码大约反映以下的行为:
void *mem = operator new(sizeof(string));
call string::string("Hands up!") on *mem;
string *ps = static_cast<string*>(mem);
也就是说operator new仅仅分配内存(就像malloc一样),我们能够做的仅仅是重载operator new,为自己的类创建一个定制的内存管理方案,这也让我有点明白为什么在重载operator new的时候并没有写调用构造函数的代码,但它确实被调用了,原来都是new operator搞的鬼。
今天看了大名鼎鼎的Scott Meyers所著的〈effective c++〉和〈more effective c++〉中关于new和delete的介绍,惊讶不已,大师果然名不虚传,研究的如此细致、透彻,让我这个菜鸟受益非浅(窃喜,呵呵)。
在C++中new operator与operator new非一回事也,new operator(即所谓的new expression)乃语言内建,咱们是没法改变其行为的,当你写string *ps = new string("Hands up!")时,你所使用的new是所谓的new operator,它其实干了两件事:一、分配足够的内存(实际大小是大于所创建的对象大小)二、调用对象构造函数,new operator永远干这两件事。上面的那段代码大约反映以下的行为:
void *mem = operator new(sizeof(string));
call string::string("Hands up!") on *mem;
string *ps = static_cast<string*>(mem);
也就是说operator new仅仅分配内存(就像malloc一样),我们能够做的仅仅是重载operator new,为自己的类创建一个定制的内存管理方案,这也让我有点明白为什么在重载operator new的时候并没有写调用构造函数的代码,但它确实被调用了,原来都是new operator搞的鬼。
相关文章推荐
- 解决Xcode 4.3.2的"Could not insert new outlet connection"问题
- error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) 已经在 LIBCMTD.lib(new.obj) 中定义
- operator new" vs. "new operator" 关系与区别
- error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in LIBCMT.
- "What's New" WebPart in SharePoint
- error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) 已经在 LIBCMTD.lib(new.obj) 中
- "today's topic is 'new age'"
- error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in LIBCMT.lib(new.obj)链接错误!
- 为什么两个CString 数据不能用"operator="
- uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operatornew(unsigned int)" (??2@YAPAXI@Z) a
- 解决Xcode 4.3.2的"Could not insert new outlet connection"问题
- VS2008(VC6)出现如下链接错误的解决方法uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsign
- VC里的"#define new DEBUG_NEW"
- VS2005(VC6)出现如下链接错误的解决方法uafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsign
- nafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z)
- nafxcwd.lib(afxmem.obj) : "void * __cdecl operator new(unsigned int)" already defined in LIBCMT.lib
- VC里的"#define new DEBUG_NEW"
- nafxcwd.lib(afxmem.obj) : error LNK2005: "void * __cdecl operator new(unsigned int)" already defined in LIBCMTD.lib(new.obj)
- "o_neww_ww_123"分割字符串split
- "new types may not be defined in a return type" error