Home  >  Q&A  >  body text

内存管理 - C和C++申请和释放内存问题

C和C++什么东西在什么时候要申请内存和释放内存(我知道的指针要释放,用delete释放)?怎么申请怎么释放?
问一个具体的问题,请不要鄙视我。Object obj;Object* obj = new Object();两种情况下,不用的时候我要释放它吗?怎么释放?
还有一个问题,比如我的对象成员有一个字符串类型的或者指针类型的变量,我在释放这个对象之前要先释放成员吗?这一步是不是必须的?

阿神阿神2715 days ago662

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:18:49

    If you use the C-style string char*, you generally need to allocate memory yourself. Of course, you need to use new to apply and then use delete to release it.
    If new is not used, this part of the memory space is opened on the stack, and there is no need to worry about memory release. If you want to do this

    Object* obj = new Object();
    

    Of course obj here needs to use delete to release the memory, or you can use smart pointers to help you manage this part of the memory, so you don’t have to manually call delete
    If your object has a member variable of pointer type, generally Next, you only need to write the steps to release the memory into the destructor, that is, write the steps to delete into the destructor.
    Generally speaking, it is necessary to release the memory of member pointer variables, because if it is not released, it will be leaked.
    However, please note that there is a pitfall in using member pointers here. When you need to copy this type of object, you need to overload the copy constructor correctly, otherwise it will cause a double free error.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:18:49

    Of course, the memory is allocated when it is needed and released when not in use.
    Using pointers will crash, so don’t use bare pointers. Why not use so many smart pointers in C++?
    Take the code in your comment as an example. If you write it like this, you won’t have to worry about it:

    std::unique_ptr<Object> ptr(new Object(...));
    ptr->...

    Then you don’t need to write delete, and the new Object will be automatically killed after the ptr goes out of scope.
    How nice.

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:18:49

    Object obj; In this way, the object does not need to be released manually in the stack space. It will be automatically released after the function stack is executed.
    Object* obj = new Object(); This way requires manual release. delete obj That’s it.
    As for the way you mentioned the existence of pointers in obj, I think you must have learned destructors when studying object-oriented. When you call delete obj, you will actually call the destructor in advance. In the destructor Just free (or delete) the pointer member

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:18:49

    The memory you apply for needs to be released by yourself. Generally, dynamic application is required when variable space is needed

    reply
    0
  • Cancelreply