C ++:静态指针,静态对象和动态内存分配 [英] C++: Static pointers, static objects and dynamic memory allocation

查看:282
本文介绍了C ++:静态指针,静态对象和动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

#include <iostream>
using namespace std;

class p
{
    public:
    int* q;
    p()
    {
        q = new int(100);
    }
    ~p(){
        delete q;
    }
};

static p* p1 = new p();
static p p2;

int main() {
    // your code goes here
    std::cout << *(p1->q);
    std::cout << *(p2.q);

    delete p1;
}

p1和p2是静态变量,它们必须存储在静态段中。 / p>

p1 and p2 are static vars, they have to stored in static segment.


  1. 由于p1是指针,是仅将指针地址存储在静态段中还是指向它的对象?

  1. since p1 is a pointer, is only the pointer address stored in static segment or even the object it points to?

p2是普通的静态对象,但是它包含动态分配的成员变量q,q也存储在静态段中吗?

p2 is a normal static object, but it contains a dynamically allocated member variable q,so is q also stored in static segment?


推荐答案


  1. p1 是一个指针,它存储在静态段中(我不确定这是正确的术语),对象或内存 p1 指向的是在堆上。

  1. p1 is a pointer, it's stored in static segment (I am not sure it's the right term), the object or memory p1 points to is on heap.

p2 是一个对象,存储在静态段中。 q p2 内的指针,对象或内存 q 指向堆中。

p2 is an object, it's stored in static segment. q is a pointer inside p2, the object or memory q points to is on heap.

这篇关于C ++:静态指针,静态对象和动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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