Is it enough to inherit from the template types of smart pointers only a class

I do not want to write in every class that I use shared_ptr or unique_ptr:

std::shared_ptr<Foo> p = CreateFoo(); 

I use this:

 template <typename T> struct ptr_types { typedef std::shared_ptr<T> sptr; typedef std::unique_ptr<T> uptr; }; class A: public ptr_types<A> { public: A(){} int m; }; 

Then I can do it:

 A::sptr p(new A); 

Is this a design issue that inherits from my classes using smart pointers? Is there a more elegant solution?

EDIT:

Yes, I can use:

 auto p = std::make_shared<A>(); 

but what about this:

 std::shared_ptr<A> A::CreateA() { .... } void A::Sink(std::unique_ptr<A> p) { ... } 

Better to have something like that?

 A::sptr A::CreateA() { ... } void A::Sink(A::uptr p) { ... } 

Maybe the question doesn't make sense ... and I'm lazy to write std :: blabla all the time in returned type functions or parameters.

+5
source share
1 answer

Creating (smart) class pointers should not be such a class responsibility. I don't think adding such behavior is a good idea, but if you want to do this, I think your creator functions should use perfect forwarding, so you can pass a parameter to the constructs:

 template<typename T, typename... Args> std::unique_ptr<T> CreateA(Args&&... args) { return std::make_shared<T>(std::forward<Args>(args)...); } 

Using std :: make_shared (and std :: make_unique, if you have C ++ 0x14) is itself a standard solution for creating cheap allocated objects. I do not think any additional solutions are needed.

0
source

Source: https://habr.com/ru/post/1213804/


All Articles