じゃあこれはどう?
int main () {
CRectangle rect (3,4); // on stack
cout << "rect area: " << rect.area() << endl;
return 0;
}
またはあなたが持っている必要prect
がある場合:
int main () {
CRectangle rect (3,4); // still on stack
CRectangle * prect = ▭ // simple alias
cout << "rect area: " << prect->area() << endl; // same as (*prect).area()
return 0;
}
しかし、少なくともあなたの単純なコードprect
では冗長です。
通常、作成時またはそれ以降に割り当てられた一部 (またはヒープに割り当てられたnew CRectangle()
から派生したクラス)が表示されることが予想されます。しかし、あなたが何をしようとしているのかはあまり明確ではありません。しかし、あなたの例では単に のエイリアスであるため、直接使用しないのはなぜですか (私の最初のコード)?CRectangle
prect
prect
rect
rect
ヒープの使用:
int main () {
CRectangle* prect = new CRectangle(3,4); // using heap
// new will throw if out of memory, so no check for null pointer needed here
cout << "rect area: " << prect->area() << endl; // same as (*prect).area()
delete prect; // free the memory - needed because it's not a stack object
return 0;
}
Mooing Duck がコメントで述べたように、STL は(C++11 で) にstd::auto_ptr
取って代わられました。std::unique_ptr
この「スマート ポインター」は、ヒープ上にあるクラスのポインターのスタック上のコンテナー クラスとして機能するため、クリーンアップも行います。
int main () {
try
{
std::auto_ptr<CRectangle> prect(new CRectangle(3,4)); // using heap, via smart ptr
// new will throw if out of memory, so no check for null pointer needed here
cout << "rect area: " << prect->area() << endl; // same as (*prect).area()
}
catch(exception& e)
{
cout << "Exception caught: " << e.what() << endl;
}
return 0;
}
との主な違いはauto_ptr
、unique_ptr
所有権に関するセマンティクスです。ウィキペディアのSmart Pointersページで概要を確認できます。