c++ - Can I apply the final keyword to a POD (standard-layout) struct in C++11 ? Should I? -
in c++ project full of objects (with proper behaviors) , relatively few of non-object-oriented structs (consisting of data fields , no methods), prevent accidental misuse of these structs, in 1 might try create class inheriting it.
according understanding, because these "pod" (plain old data) structs not have virtual destructor, not possible delete derived class object (if 1 allowed create it) via pointer of pod type.
this seems make use case c++11 "final" keyword, marks class or struct non-inheritable.
however, wonder if "final" keyword causes struct become non-pod?
i suspect standards documentation may have addressed issue, not intelligent enough sift through long documentations find out. useful pointers welcome.
note: not interested in merely knowing passes compilation of compiler vendors. passing compilation not guarantee:
- whether compiled code execute correctly in situations (especially when technique applied in larger, more complex project),
- whether c++ standards body intends used in way.
#include <iostream> using namespace std; struct pod final { int a; int b; int c; }; #if 0 class failsbecausecannotderivefromfinalanything : public pod { }; #endif class containssomethingfinalasmember { public: containssomethingfinalasmember() : pod() {} private: pod pod; }; int main() { std::cout << std::is_pod < pod > :: value << std::endl; return 0; }
according understanding, because these "pod" (plain old data) structs not have virtual destructor, not possible delete derived class object (if 1 allowed create it) via pointer of pod type.
it's not possible given raw pointer, possible given smart pointer object, such std::shared_ptr
or std::unique_ptr
appropriate deleter.
since smart pointers standardized, there few excuses continue following poor practice of using delete
operator manually. certainly, classes shouldn't designed around compatibility delete
operator. each class interface should designed particular uses in mind.
no, it's not practice make every class either final
or polymorphic.
however, wonder if "final" keyword causes struct become non-pod?
no, it's still pod. requirements pod standard layout (in turn requiring no base class, no access specifiers between members, no virtual anything) , trivial special member functions (copy/move constructor, assignment operator, destructor).
however, purpose of pod-ness allow use memcpy
instead of constructing objects, c++ code avoid doing.
Comments
Post a Comment