Code Monkey home page Code Monkey logo

Comments (4)

tnie avatar tnie commented on August 9, 2024 1

以下描述貌似和上文相悖:

析构函数一般用来释放对象所分配的资源。例如,string 构造函数(以及其他 string 成员)会分配内存来保存构成 string 的字符。string 析构函数就负责释放这些内存。类似的,vector 的若干操作都会分配内存来保存其元素。vector 析构函数就负责销毁这些元素,并`释放它们所占用的内存。 引用自《C++ Primer》第 402 页

string vector 是容器,它们的构造、析构中是妥妥的动态分配内存、释放内存的。

from quote-demo.

tnie avatar tnie commented on August 9, 2024

其实给我带来惊讶的是跳出自己思维盲区的一个操作:竟然还可以显式地调用析构函数。

显式调用构造函数也是可以的。

https://blog.csdn.net/jnu_simba/article/details/8803377

from quote-demo.

tnie avatar tnie commented on August 9, 2024

“显式调用析构函数并不释放内存” 标题给人误解:不显式调用析构函数就会释放内存似的。实际上正如前文描述,析构只负责销毁对象(有时会包含「释放动态申请的内存」任务),虽然和内存释放组合在一起,但释放内存并不是由析构函数带来的。

from quote-demo.

tnie avatar tnie commented on August 9, 2024

显式析构带来的直接影响就是二次析构,具体是否会带来不良影响需要看具体的业务逻辑。

void test()
{
    auto ptr = new Person(1);
    ptr->~Person();
    ptr->echo();
    delete ptr;
}

void test2()
{
    Person ins(33);
    ins.echo();
    ins.~Person();
    //ins.echo();
}

最可能的负面影响就是当析构中释放动态内存时,如果未作判断直接释放就会抛出堆异常。

Person::~Person()
{
    cout << "~Person" << endl;
    //if (p)
    {
        delete p;
        //p = nullptr;
    }
}

from quote-demo.

Related Issues (18)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.