c++ - 在堆栈上创建类实例

标签 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";
}

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

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

最佳答案

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

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

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

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

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
}

另一方面,您应该删除使用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";
}

另请参阅:When should I use the new keyword in C++?

关于c++ - 在堆栈上创建类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556091/

相关文章:

c++ - 在结构内部的 TR1 unordered_map 中定义哈希函数

c++ - 为没有继承的模板参数类提供构造函数

c++ - 加密程序错误

c++ - C 和 C++ 中 '.' 和 '->' 运算符的正式名称是什么?

c++ - 为什么我构造的临时对象 const 不可变?

c++ - 通过 boost::bind 从 vector 中删除字符串

c++ - 如何使用初始化列表初始化不可复制的容器?

c++ - WinHTTP 是在下载空字节还是我错误地复制了结果缓冲区?

c++ - Linux 的 fork 函数与 Windows 的 CreateProcess 相比——复制了什么?

c++ - 执行时溢出/下溢是未定义的行为吗?