c++ - Can we hide unimportant declarations in Header files? -
i decided export of functions static library (.lib). decided not give complete header files users. kept private , protected variables , methods out of it, end-users should not use them , should not have include other headers class declarations.
unexpectedly ran heap-corruption errors when creating instances of classes exported static lib.
this original header file:
// original header file class codbchelper { public: codbchelper(); virtual ~codbchelper(); public: std::vector<userdata> getuserinformation(); private: sqlhenv m_henv; sqlhdbc m_hdbc; sqlhstmt m_hstmt; };
then decided take private variables out, users of .lib not abuse them , not have include unnecessary sql header files:
// minimized header file class codbchelper { public: codbchelper(); virtual ~codbchelper(); public: std::vector<userdata> getuserinformation(); };
i noticed sizeof
operation returns different values depending called.
called in .lib:
int size = sizeof(codbchelper); // size 12
called in linking project:
int size = sizeof(codbchelper); // size 1
doing following code in linking project causes heap corruption (which happens because of wrong size calculations):
codbchelper* helper = new codbchelper;
doing like
class codbchelper { [...] private: char padding[12]; }
would solve problem, think bad behavior , not maintainable @ all.
so there way tell compiler how big real object (from linked library) going be? or there easy way of hiding declarations in header files not needed users?
i don't see how "hiding unimportant members" connected removing them class definition.
i guess, wanted eliminate unnecessary dependencies code. technique - reduces compilation time, makes code more portable between different versions , more.
the thing is, changed class completely. if designed have 3 private members:
sqlhenv m_henv; sqlhdbc m_hdbc; sqlhstmt m_hstmt;
you cannot remove them. not "hiding implementation details" means.
or there easy way of hiding declarations in header files not needed users?
what want use pimpl idiom:
//minimized header file class codbchelper { public: codbchelper(); virtual ~codbchelper(); public: std::vector<userdata> getuserinformation(); private: struct internaldata; internaldata* m_internal_data; };
then, in .cpp
file:
struct codbchelper::internaldata { sqlhenv m_henv; sqlhdbc m_hdbc; sqlhstmt m_hstmt; };
now change implementation use m_internal_data
instead of each component separately. profitable if software updated - forbids clients create code, depends on implementation details of types.
you may want read point 2. and/or 4. of this answer.
Comments
Post a Comment