0

I want to write some easy-to-call object initializiation and I would like those objects to be shared_ptr of MyClass.

Just for visualisiation purposes, imagine this class:

class MyClass
{
public:
  MyClass(int number);
  MyClass(wxString path);
}

int main()
{
  //For now, objects are created in c style like this:
  MyClass obj1("C:\\test");
  MyClass * obj2 = new MyClass(5);
}

Now I would like to change this with easy to use smart pointer initialization. My goal is something looking like a constructor call, so that very little has to be changed to update the old call to the new one:

Smart_MyClass obj1("C:\\test");
Smart_MyClass obj2(5);
//where Smart_MyClass is std::shared_ptr<MyClass> 

I could solve this with a function:

template<typename T>
inline Smart_MyClass Smart_MyClass_Fct(T t)
{
    return std::make_shared<MyClass>(t);
};

Smart_MyClass obj = Smart_MyClass_Fct(7);

How can I translate that into the form I need? I could think of using the operator(), that would require a struct/class and maybe inheritence of my actual class? And maybe casting it back to parent class? Pretty sure there is something more elegant. ;-)

4

1 回答 1

0

您可以尝试以下方法:

template<typename T>
class SharedWrapper
{
public:
    template<typename... Args>
    SharedWrapper(Args... args) : 
        m_p{std::make_shared<T>(std::forward<Args>(args)...)}
    { }

    T& operator*() const noexcept { return *m_p; }
    T* operator->() const noexcept { return m_p.operator->(); }
    explicit operator bool() const noexcept { return static_cast<bool>(m_p); }

private:
    std::shared_ptr<T> m_p;
};

这只是将构造函数的参数转发给make_shared函数,然后镜像智能指针的接口。(在这里您可能需要根据需要添加其他转发方法。)

和:

using Smart_MyClass = SharedWrapper<MyClass>;

您应该获得所需的行为,也可以将其用于不同的类。

但是,我认为Smart_MyClass实际上没有任何可能成为std::shared_ptr<MyClass>. 不鼓励继承,shared_ptr因为它没有虚拟析构函数。这也可能会限制这种方法的可用性。

除了风格之外,还有什么理由让你想使用这个符号吗?

于 2019-10-16T13:02:25.343 回答