放置新的和例外 [英] placement new and exception
问题描述
在 http://www.parashift。 com / c ++ - faq-lit ... tore-mgmt.html
in [16.9]在p = new Fred()中,Fred内存是否泄漏如果Fred
构造函数抛出异常?
有这段代码:
//原始代码:Fred * p =新Fred();
Fred * p =(Fred *)operator new(sizeof(Fred));
尝试{
new( p)Fred(); //安置新
} catch(...){
operator delete(p); //释放内存
throw; //重新抛出异常
}
可以放置新的什么异常???
On http://www.parashift.com/c++-faq-lit...tore-mgmt.html
in [16.9] In p = new Fred(), does the Fred memory "leak" if the Fred
constructor throws an exception?
there is this code:
// Original code: Fred* p = new Fred();
Fred* p = (Fred*) operator new(sizeof(Fred));
try {
new(p) Fred(); // Placement new
} catch (...) {
operator delete(p); // Deallocate the memory
throw; // Re-throw the exception
}
What exception can placement new throw???
推荐答案
" wijhierbeneden"写道:
"wijhierbeneden" wrote:
什么异常可以放置新抛出???
What exception can placement new throw???
构造函数抛出的那些。
/ Pavel
Those thrown by constructor.
/Pavel
Fred * p =(Fred *)operator new(sizeof(Fred));
Fred* p = (Fred*) operator new(sizeof(Fred));
我不认识上面的语法。
怎么样 :
Fred * p = reinterpret_cast< Fred * const&>(new char [sizeof(Fred)]);
I don''t recognize the syntax above.
How about:
Fred* p = reinterpret_cast<Fred* const &>( new char[sizeof(Fred)] );
>
JKop写道:
JKop wrote:
Fred * p =(Fred *)operator new(sizeof(Fred));
Fred* p = (Fred*) operator new(sizeof(Fred));
我不认识上面的语法。
怎么样:
Fred * p = reinterpret_cast< Fred * const&>(new char [sizeof(Fred)]);
I don''t recognize the syntax above.
How about:
Fred* p = reinterpret_cast<Fred* const &>( new char[sizeof(Fred)] );
它可以使用重载的运算符函数并访问它
直接。例如:
myclass& operator +(myclass& a,myclass& b)
{
} < br $>
....
....
myclass yy,zz,ss;
ss = operator +(yy,zz);
与以下内容相同:
ss = yy + zz;
在极少数情况下这很有用......
David
it is valid to take an overloaded operator function, and access it
directly. For example:
myclass &operator +(myclass &a, myclass &b)
{
}
....
....
myclass yy,zz ,ss;
ss = operator +(yy,zz) ;
is the same as:
ss = yy + zz ;
in rare circumstances this is useful...
David
这篇关于放置新的和例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!