在堆栈上创建类实例

Sho*_*ker 2 c++

我正在尝试使用 C++ 中的内存,我为自己定义了一个类,然后在堆内创建了该类的实例。

#include <iostream>

class mojeTrida {
  public:
  
  void TestPrint()
  {
    std::cout << "Ahoj 2\n";
  }
};

int main() {
  mojeTrida *testInstance = new mojeTrida();
  
  testInstance->TestPrint();
  
  std::cout << "Hello World!\n";
}
Run Code Online (Sandbox Code Playgroud)

如果我正确理解了 c++,每当我调用关键字“new”时,我都会要求操作系统给我一定数量的字节来在堆内存储类的新实例。

有什么办法可以将我的类存储在堆栈中吗?

Mel*_*ius 10

在堆栈上创建对象(即类实例)的方法更简单——局部变量存储在堆栈中。

int main() {
  mojeTrida testInstance;  // local variable is stored on the stack
  
  testInstance.TestPrint();
  
  std::cout << "Hello World!\n";
}
Run Code Online (Sandbox Code Playgroud)

正如您根据您的评论所注意到的.->在调用对象的方法时使用运算符而不是。->仅与指针一起使用以取消引用它们并同时访问它们的成员。

带有指向局部变量的指针的示例:

int main() {
  mojeTrida localInstance;  // object allocated on the stack
  mojeTrida *testInstance = &localInstance; // pointer to localInstance allocated on the stack
  
  testInstance->TestPrint();
  
  std::cout << "Hello World!\n";
  // localInstance & testInstance freed automatically when leaving the block
}
Run Code Online (Sandbox Code Playgroud)

另一方面,您应该delete使用new以下方法在堆上创建对象:

int main() {
  mojeTrida *testInstance = new mojeTrida();  // the object allocated on the heap, pointer allocated on the stack
  
  testInstance->TestPrint();

  delete testInstance;  // the heap object can be freed here, not used anymore
  
  std::cout << "Hello World!\n";
}
Run Code Online (Sandbox Code Playgroud)

另请参阅:何时应该在 C++ 中使用 new 关键字?

  • 不,在堆栈示例中,“testInstance”的类型是“mojeTrida”,在堆示例中,类型是“mojeTrida*”(指针)。这就是 `.` 与 `-&gt;` 的区别。您仍然可以获得指向堆栈实例的指针,例如`mojeTrida testInstance; mojeTrida* testInstancePtr = &amp;testInstance; testInstancePtr-&gt;TestPrint();` ...只需注意堆实例保持分配状态直到被删除,堆栈实例内存在“{}”块的末尾被释放,因此指向它的任何指针都变得毫无意义(指向内存)未使用或被其他代码块使用)。 (2认同)