What other ways to initialize(allocate memory) data members of class in c++ other than constructors? -
suppose don't have constructors other way initialize data members of class?? _init() methods? considering have allocate memory data members.
if don't know value assign field, can mean 2 things:
- mostly, means don't have class @ all. note in c++, class not 'collecting storage' data until have (we have separate pattern/anti-pattern called builder that), in case shouldn't create class. might consider having several more classes that's modelled after data have @ point.
- sometimes, it's valid class either have or not have data; is, data optionally part of class per class invariant. in case, use
std::optional<>
member, can initializednullopt
. might usestd::optional<>
avoid polluting otherwise clean resource classes invalid state (that is, potentially open resourcestd::optional<t>
, surely opent
)
do not default-initialize fields don't know yet: you're wasting time , possibly, space. do not use pointers delay construction: pointers sharing amongst classes - this, you'd wasting lot of time (due nullptr
check in members) , force dynamic allocation unnecessary. use std::optional<>
when don't need sharing, prefer classes known members. try simplify invariant class keeps, not construction of it. you'll find makes write loops , calls in optimal order reusing data in long term.
Comments
Post a Comment