Explicitly deleting a shared_ptr

前端 未结 5 1738
遇见更好的自我
遇见更好的自我 2021-02-01 16:37

Simple question here: are you allowed to explicitly delete a boost::shared_ptr yourself? Should you ever?

Clarifying, I don\'t mean delete the pointer held

5条回答
  •  梦毁少年i
    2021-02-01 17:14

    Expliticly deleting comes in handy in some (very?) rare cases.

    In addition to explicitly deleting, sometimes you HAVE to explicitly destruct a shared pointer when you are 'deleting' it!

    Things can get weird when interfacing with C code, passing a shared_ptr as an opaque value.

    For example I have the following for passing objects to and from the Lua scripting language which is written in C. (www.lua.org)

    static void push( lua_State *L, std::shared_ptr sp )
    {
        if( sp == nullptr ) {
            lua_pushnil( L );
            return;
        }
    
        // This is basically malloc from C++ point of view.
        void *ud = lua_newuserdata( L, sizeof(std::shared_ptr));
    
        // Copy constructor, bumps ref count.
        new(ud) std::shared_ptr( sp );
    
        luaL_setmetatable( L, B::class_name );
    }
    

    So thats a shared_ptr in some malloc'd memory. The reverse is this... (setup to be called just before Lua garbage collects an object and 'free's it).

    static int destroy( lua_State *L )
    {
        // Grab opaque pointer
        void* ud = luaL_checkudata( L, 1, B::class_name );
    
        std::shared_ptr *sp = static_cast*>(ud);
    
        // Explicitly called, as this was 'placement new'd
        // Decrements the ref count
        sp->~shared_ptr();
    
        return 0;
    }
    

提交回复
热议问题