c++ - One definition rule warning -


i have been bitten nasty "one definition rule" violation. afraid of having lots of subtle bugs in projects.

for example, following program result in null pointer dereference visual studio 2015:

source1.cpp: ---------- struct s {     double d = 0; };  void foo() {     s s; }   source2.cpp: ----------- struct s {     int = 0; };  int main() {      int value = 5;     int& valueref = value;     s s;           // valueref erased due s::d initialization source1.cpp      valueref++;    // crash } 

this compiles no warnings.

it's nasty because source2.cpp doesn't use source1.cpp. if remove source1.cpp project, still compiles, , there no problem anymore.

in large projects, seems hard ensure no cpp file "locally" define struct or class defined name.

i have classes such point, serie, state, item, ... though ok in small cpp files, realize it's not safe.

is there compiler warning catch such bugs ? if not, best practices avoid odr violation ?

in particular case, @ bottom odr violation (which leads problem observing) implicitly-defined inline constructor of class s. program has 2 non-matching versions of inline s::s() function, can seen odr violation induced original odr violation (i.e. same class defined differently).

it difficult implementation "see" error in current approach c++ compilation infrastructure. of course, possible sufficient effort.

in case in order make error "visible" can explicitly declare , define class constructor non-inline function empty body. presence of 2 non-inline s::s() trigger linker error.

understandably, might see overly artificial measure, unacceptable in cases since might change "aggregate" status of class.


Comments

Popular posts from this blog

Formatting string according to pattern without regex in php -

c - zlib and gdi32 with OpenSSL? -

java - inputmismatch exception -