オブジェクトがC++のブロック内に作成された場合、オブジェクトはどこに格納されますか?
このセクションでは、C++プログラムのコンパイル時に変数とオブジェクトがメモリ内のどこに格納されるかについて説明します。ご存知のように、オブジェクトを保存できるメモリには2つの部分があります-
-
スタック −メモリのブロック内で宣言されたすべてのメンバーは、スタックセクション内に格納されます。 main関数も関数であるため、その中の要素はスタック内に格納されます。
-
ヒープ −一部のオブジェクトが動的に割り当てられると、それはヒープセクション内に格納されます。
ブロックまたは関数内で宣言されたオブジェクトのスコープは、それが作成されたブロックに限定されます。オブジェクトは、ブロック内に作成されたときにスタックに格納され、コントロールがブロックまたは関数を終了すると、オブジェクトは削除または破棄されます。
動的に割り当てられたオブジェクトの場合(実行時)、オブジェクトはヒープに格納されます。これは、新しいオペレーターの助けを借りて行われます。そのオブジェクトを破棄するには、delキーワードを使用して明示的に破棄する必要があります。
例
理解を深めるために、次の実装を見てみましょう-
#include <iostream>
using namespace std;
class Box {
int width;
int length;
public:
Box(int length = 0, int width = 0) {
this->length = length;
this->width = width;
}
~Box() {
cout << "Box is destroying" << endl;
}
int get_len() {
return length;
}
int get_width() {
return width;
}
};
int main() {
{
Box b(2, 3); // b will be stored in the stack
cout << "Box dimension is:" << endl;
cout << "Length : " << b.get_len() << endl;
cout << "Width :" << b.get_width() << endl;
}
cout << "\tExitting block, destructor" << endl;
cout << "\tAutomatically call for the object stored in stack." << endl;
Box* box_ptr;{
//Object will be placed in the heap section, and local
pointer variable will be stored inside stack
Box* box_ptr1 = new Box(5, 6);
box_ptr = box_ptr1;
cout << "---------------------------------------------------" << endl;
cout << "Box 2 dimension is:" << endl;
cout << "length : " << box_ptr1->get_len() << endl;
cout << "width :" << box_ptr1->get_width() << endl;
delete box_ptr1;
}
cout << "length of box2 : " << box_ptr->get_len() << endl;
cout << "width of box2 :" << box_ptr->get_width() << endl;
} 出力
Box dimension is: Length : 2 Width :3 Box is destroying Exitting block, destructor Automatically call for the object stored in stack. --------------------------------------------------- Box 2 dimension is: length : 5 width :6 Box is destroying length of box2 : 0 width of box2 :0
-
C ++標準出力ストリーム(cout)とは何ですか?
std ::coutは、クラスostreamのオブジェクトであり、(char型の)狭い文字に向けられた標準出力ストリームを表します。 Cストリーム標準に対応します。標準出力ストリームは、環境によって決定される文字のデフォルトの宛先です。この宛先は、より標準的なオブジェクト(cerrやclogなど)と共有される場合があります。 クラスostreamのオブジェクトとして、文字は、挿入演算子(operator <<)を使用してフォーマットされたデータとして、またはwriteなどのメンバー関数を使用してフォーマットされていないデータとして書き込むことができます。オブジェクトは、外部リンケージと静的期
-
C ++でPythonオブジェクトを使用する方法は?
これは、単純なPythonオブジェクトがラップされて埋め込まれている例です。これには.cを使用していますが、c++にも同様の手順があります- class PyClass(object): def __init__(self): self.data = [] def add(self, val): self.data.append(val) def __str__(self):