在堆栈上创建类实例
Create class instance on stack
我试图在C++中玩一点内存,我给自己定义了一个类,然后在堆中创建该类的实例。
#include <iostream>
class mojeTrida {
public:
void TestPrint()
{
std::cout << "Ahoj 2n";
}
};
int main() {
mojeTrida *testInstance = new mojeTrida();
testInstance->TestPrint();
std::cout << "Hello World!n";
}
如果我正确理解了 c++,那么每当我调用关键字"new"时,我都会要求操作系统给我一定数量的字节来在堆中存储一个新的类实例。
有什么方法可以将我的类存储在堆栈中吗?
在堆栈上创建对象(即.class实例(的方法甚至更简单 - 局部变量存储在堆栈上。
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
delete
堆上创建的对象:
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";
}
另请参阅:何时应在C++中使用 new 关键字?
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 在C++中为链表类创建实例
- 如何为类的每个实例创建特定实例的方法
- 基于现有实例创建类的新实例
- 从模板类的另一个实例创建模板类的实例时省略模板参数
- Vulkan-加载扩展时实例创建失败
- 通知B1或B2或B3类的特定实例创建Pointer A类
- 使用std::shared_ptr对象实例创建boost::线程
- 如何在C++中仅包含一个实例创建类
- 如何从旧实例创建新实例
- 在V8 javascript引擎中,如何为每个实例创建一个重新使用ObjectTemplate的构造函数
- 有没有一种方法可以从基本实例创建派生实例
- 如何在修改设计时停止现有代码基类的实例创建
- 使用基类实例创建派生类实例
- 如何从另一个仅静态选择满足特定类型规则的索引的元组实例创建元组实例