• c++ Dynamic Memory (part 2)


    Don't use get to initialize or assign another smart pointer.

    The code that use the return from get can not delete the pointer

    Although the compiler will not complain, it is an error to build another smart pointer to the pointer returned by get

    shared_ptr<int> p(new int(42));    // reference count is 1
    int *q = p.get();    // ok; but do not delete its pointer
    {
        shared_ptr<int> (q);
    }    // block ends. q is destroyed, and the memory to which q points is freed
    int f = *p;    // undefined. The memory to which p points is freed. 

    Using Our Own Deletion Code

    void end_connection(connection *p)
    {
        disconnection(*p);
    }
    
    void f(destination &d)
    {
        connection c = conn(&d);
        shared_ptr<connection p(&c, end_connection);
        // use the connection
        // when f exists, even if by an exception, the connection resource will be properly closed
    }

    For unique_ptr

    Call release() breaks the connection between a unique_ptr and the object it had been managing. Ofter the pointer returned by release() is used to initialized or assign another pointer

    unique_ptr<int> p2(new int(42));
    p2.release();    // WRONG! P2 will not free the memory, and we have lose the pointer
    auto p = p2.release();    // OK, but we must remember to delete p

    Backward compatibilities auto_ptr

    Although auto_ptr is still part of the standard library, programs should use unique_ptr instead.

  • 相关阅读:
    GFS读后笔记
    BigTable读后笔记
    恢复系统基础理论
    事务基础理论
    ARIES算法简介
    怎么快速构建自己的C/C++程序?——有关编译、静态链接和SCons
    lua学习笔记
    运行时动态伪造vsprintf的va_list
    11月30日站立会议
    11月29号站立会议
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/6854544.html
Copyright © 2020-2023  润新知