c ++指针范围 [英] c++ pointer scope

查看:137
本文介绍了c ++指针范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您拥有以下代码时会发生什么:

What happens when you have the following code:

void makeItHappen()
{
    char* text = "Hello, world";
}

text go

下面的例子:

class SomeClass
{
    public:
      SomeClass();
      ~SomeClass();
};

SomeClass::SomeClass() { }
SomeClass::~SomeClass()
{
    std::cout << "Destroyed?" << std::endl;
}

int main()
{
    SomeClass* someClass = new SomeClass();
    return 0;
} // What happend to someClass?

这里有同样的事情吗?

谢谢!

推荐答案

 char* text = "Hello, world";

这里在堆栈上创建一个自动变量(指针),并设置为指向常数内存,表示:

Here an automatic variable (a pointer) is created on the stack and set to point to a value in constant memory, which means:



  • 您不负责分配或释放

  • 您不能更改它。

当指针指向一个指针时,如果你想改变它,那么你必须分配一些非常量内存超出范围,内存指针本身(4字节)被释放,并且字符串仍然在同一位置 - 常量内存。

When the pointer goes out of scope, the memory pointer itself (4 bytes) is freed, and the string is still in the same place - constant memory.

对于后者:

SomeClass* someClass = new SomeClass();

然后 someClass 它超出范围(因为指针本身也在堆栈上,只是在第一个例子)... 但不是对象!

Then someClass pointer will also be freed when it goes out of scope (since the pointer itself is on the stack too, just in the first example)... but not the object!

关键字 new 基本上意味着您在免费存储上为对象分配了一些内存 - 并且您负责调用 delete 有时为了释放内存。

The keyword new basically means that you allocate some memory for the object on free store - and you're responsible for calling delete sometime in order to release that memory.

这篇关于c ++指针范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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