如果我们创建类的对象而不在C ++中使用new,那么该对象是在堆上创建的吗? [英] If we create object of a class without using new in C++, is this object is created on heap?

查看:62
本文介绍了如果我们创建类的对象而不在C ++中使用new,那么该对象是在堆上创建的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
1)我知道用new初始化的东西都在堆上.但是,如果我们在C ++中创建类的对象而不使用new的话,


MyClass obj();


1)在声明它的地方是堆栈还是堆?
2)它在有内存的地方初始化,堆栈还是堆?

Hello,
1) I know that things initialized with new are on heap. But If we create object of a class without using new in C++,


MyClass obj();


1)Where it is declared,stack or heap??
2) Where it has memory,initializes,stack or heap?

推荐答案

该对象将在堆栈​​上创建,然后在离开函数的途中销毁

Data段用于在任何函数范围之外声明的所有变量

堆栈用于函数内声明的所有变量.在以下示例中

That object would be created on the stack, and then destroyed on the way out of the function

The Data segment is used for all variables declared outside the scope of any function

The stack is used for all variables declared within a function; in the following example

void afunction()
{
   MyClass *pMyClass=new MyClass();
}


指针是该函数(在堆栈上)的局部指针,但该类在堆上


The pointer is local to the function (on the stack) but the class is on the heap


您必须注意,在C ++中,MyClass obj();将是一个名为<的函数的声明. c1>返回类型为MyClass的对象.

要在堆栈上实际创建一个对象,您必须删除括号并写:

You have to be aware that in C++ MyClass obj(); would be a declaration of a function named obj that returns an object of type MyClass.

To actually create an object on the stack, you will have to remove the parenthesis and write:

void someFunction()
{
  MyClass obj; // object on the stack
}


这篇关于如果我们创建类的对象而不在C ++中使用new,那么该对象是在堆上创建的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆