Factory in secure basic access ctor in derivative

I want all objects derived from Initable to call terminate() on destruction. To do this, I create shared_ptr with user deletion.

My problem is that I cannot access the protected ctor of derived classes to create an instance in the Initable factory method.

Ctor must be protected to prevent instantiation without using the factory method.

 class Initable { public: virtual void terminate() = 0; template<typename T, typename... Ts> static shared_ptr<T> make_initable(const Ts &... args) { return shared_ptr<T>(new T(std::forward<const Ts>(args)...), [] (Initable * aptr) { cout << "custom deleter" << endl; }); } }; class B : public Initable { friend class Initable; // ... }; 

I would like to avoid declaring as a friend of each derived class, what can I do?

+6
source share
1 answer

No friends:

  • symmetrical.
  • transitively.
  • inherited.

This, I think, leaves you with the opportunity to help your user know that he missed the friendship declaration in Initable class. You cannot use specialized specialization for this, because the declaration of the declaration must occur within the scope of the class and the declaration of the template must occur in the scope of the namespace.

One way to do this:

 #define DECLARE_INITABLE \ constexpr static bool is_Initable_friend = true;\ friend class Initable; class Initable { public: virtual void terminate() = 0; template<typename T, typename... Ts> static shared_ptr<T> make_initable(const Ts &... args) { static_assert(T::is_Initable_friend, "Please call DECLARE_INITABLE in your class declaration"); return shared_ptr<T>(new T(std::forward<const Ts>(args)...), [] (Initable * aptr) { cout << "custom deleter" << endl; }); } }; class B : public Initable { // DECLARE_INITABLE ... }; 
+1
source

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


All Articles