在堆栈上创建类实例

Create class instance on stack

本文关键字:实例 创建 堆栈      更新时间:2023-10-16

我试图在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
}

另一方面,您应该使用newdelete堆上创建的对象:

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 关键字?