Operator new allocates memory from the heap, on which an object is constructed. Standard C++ also supports placement new operator, which constructs an object on a pre-allocated buffer. This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-allocated buffer takes less time):
 void placement() {

char *buf = new char[1000]; //pre-allocated buffer

string *p = new (buf) string("hi"); //placement new

string *q = new string("hi"); //ordinary heap allocation

cout<
<
c_str()
<
<c_str();

}

placement new 表达式只是定位,不存在与其相对应的delete,如果delete则选择
delete[] buf。


michalegao 2008-06-05 12:03 发表评论

文章来源:http://www.cnblogs.com/michael-gao/archive/2008/06/05/1214239.html
Posted on 2008-06-05 15:59 micheal's tech 阅读(234) 评论(0)  编辑 收藏 引用 所属分类: C++ programme language

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理