How to force only smart pointers instance for a class?

后端 未结 2 1810
庸人自扰
庸人自扰 2021-02-04 10:53

I\'ve been working on a way to prevent user of using a class without smart pointers. Thus, forcing them to have the object being heap allocated and managed by smart pointers. In

2条回答
  •  我在风中等你
    2021-02-04 11:14

    As there is no general term "smart pointer" what you want is not possible.

    What you can do, is supporting some known set of smart pointers. The usual solution starts as yours, making ctor or dtor private, and adds factory functions. That can return the instance packed with your desired smart pointers. If you just want to support unique_ptr and shared_ptr, that meaans two factory functions, hardly too much. (note that those pointers allow smuggling out the raw pointer through simple interface so the control is not full.)

提交回复
热议问题