简体   繁体   English

从类似构造函数的调用中返回模板化智能指针

[英]Return templated smart pointer from constructor-like calls

I want to write some easy-to-call object initializiation and I would like those objects to be shared_ptr of MyClass.我想写一些易于调用的 object 初始化,我希望这些对象是 MyClass 的 shared_ptr。

Just for visualisiation purposes, imagine this class:仅出于可视化目的,想象一下这个 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:我可以用 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?我可以考虑使用 operator(),这将需要一个结构/类,并且可能需要继承我的实际 class? And maybe casting it back to parent class?也许将其转换回父 class? Pretty sure there is something more elegant.很肯定有更优雅的东西。 ;-) ;-)

You could try something along these lines:您可以尝试以下方法:

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;
};

This just forwards the arguments of the constructor to the make_shared functions and then mirrors the interface of the smart pointer.这只是将构造函数的 arguments 转发给make_shared函数,然后镜像智能指针的接口。 (Here you might have to add additional forwarding methods as needed.) (在这里您可能需要根据需要添加其他转发方法。)

With:和:

using Smart_MyClass = SharedWrapper<MyClass>;

you should get the desired behavior and can also use this for different classes.您应该获得所需的行为,也可以将其用于不同的类。

However I don't see any possibility to have Smart_MyClass actually be a std::shared_ptr<MyClass> .但是,我认为Smart_MyClass实际上没有任何可能成为std::shared_ptr<MyClass> Inheriting from shared_ptr is discouraged since it does not have a virtual destructor.不鼓励从shared_ptr继承,因为它没有虚拟析构函数。 This might also limit the usability of this approach.这也可能会限制这种方法的可用性。

Is there any reason besides style that makes you want to use this notation?除了风格之外,还有什么理由让你想使用这个符号吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM