Home > Net >  pass stack variable to function that takes a std::shared pointer
pass stack variable to function that takes a std::shared pointer

Time:10-18

If I have a global variable, or a stack variable can I pass it to a function that takes a std::shared_ptr with a templated class like this:

template<class T> class shared_ptr_stack:public std::shared_ptr<T> {
    public:
    shared_ptr_stack(T * target):std::shared_ptr<T>(target, [](T * t){}){};
    };
};

The goal would be to avoid destructing or deleting memory when there are no references left. The code compiles and works in tests, but I am concerned I am invoking undefined behaviour or some other negative issue.

CodePudding user response:

A function that takes a shared ptr has the right to make your data persist indefinitely. It can pass your data to different structures, threads, whatever.

Your code means that the data becomes trash when the stack frame goes out of scope, or at static destruction time, either of which can be before the last shared ptr copy dies.

An API taking a shared ptr is asking for that right. You are lying to it.

Other than that, your code is fine. I would use a factory function instead of a subclass however. You could also use aliasing ctor of shared ptr to get some RAII based reporting.

  • Related