c++ - Ensure safety while using CRTP -
consider following snippet of code making using of crtp
#include <iostream> struct alone { alone() { std::cout << "alone constructor called" << std::endl; } int me {10}; }; struct dependant { explicit dependant(const alone& alone) : ref_alone(alone) { std::cout << "dependant called alone's me = " << alone.me << std::endl; } const alone& ref_alone; void print() { std::cout << ref_alone.me << std::endl; } }; template <typename d> struct base { base() { std::cout << "base constructor called" << std::endl; } d* getderived() { return static_cast<d*>(this); } dependant f { getderived()->alone }; void print() { f.print(); } }; struct derived : base <derived> { derived() { std::cout << "derived constructor called " << std::endl; } alone alone {}; void print() { base::print(); }; }; int main() { derived d; d.print(); }
original link http://coliru.stacked-crooked.com/a/79f8ba2d9c38b965
i have basic question first
how memory allocation happen when using inheritance? know constructors called base derived, seems when do
derived d;
memory equivalent sizeof(d) allocated, , constructors called. understanding correct here? (this explain printing uninitialised member)
considering above example in mind, suggest/recommend best practices when comes crtp?
memory equivalent sizeof(d) allocated, , constructors called
how else possibly work? can't construct object in memory isn't allocated yet. memory allocation comes before object construction.
considering above example in mind, suggest/recommend best practices when comes crtp?
the standard practices crtp: don't call crtp in constructor/destructor. true of virtual functions. virtuals dynamic polymorphism, while crtp static polymorphism. they're both using same basic mechanism: base class defines interface derived class must implement.
and virtual functions, trying call in constructors/destructors won't mean. difference virtual functions, compiler keep getting undefined behavior. whereas crtp, breakage.
note includes default member initializers, purpose of non-aggregates shorthand constructor initialization lists.
Comments
Post a Comment