Explicitly deleting a shared_ptr

前端 未结 5 1737
遇见更好的自我
遇见更好的自我 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:23

    If you want to simulate the count decrement, you can do it manually on the heap like so:

    int main(void) {
        std::shared_ptr* sp = new std::shared_ptr(std::make_shared(std::string("test")));
        std::shared_ptr* sp2 = new std::shared_ptr(*sp);
        delete sp;
    
        std::cout << *(*sp2) << std::endl;    // test
        return 0;
    }
    

    Or on the stack using std::shared_ptr::reset() like so:

    int main(void) {
        std::shared_ptr p = std::make_shared(std::string("test"));
        std::shared_ptr p2 = p;
        p.reset();
    
        std::cout << *p2 << std::endl;    // test
        return 0;
    } 
    

    But it's not that useful.

提交回复
热议问题