Discussion
Team LiB
Previous Section Next Section

Discussion

memcpy and memcmp violate the type system. Using memcpy to copy objects is like making money using a photocopier. Using memcmp to compare objects is like comparing leopards by counting their spots. The tools and methods might appear to do the job, but they are too coarse to do it acceptably.

C++ objects are all about information hiding (arguably the most profitable principle in software engineering; see Item 11): Objects hide data (see Item 41) and devise precise abstractions for copying that data through constructors and assignment operators (see Items 52 through 55). Bulldozing over all that with memcpy is a serious violation of information hiding, and often leads to memory and resource leaks (at best), crashes (worse), or undefined behavior (worst). For example:



{


  shared_ptr<int> p1( new int ), p2( new int );   // create two ints on the heap


  memcpy( &p1, &p2, sizeof(p1) );               // bad: a heinous crime


}// memory leak: p2's int is never deleted


 // memory corruption: p1's int is deleted twice



Abusing memcpy can affect aspects as fundamental as the type and the identity of an object. Compilers often embed hidden data inside polymorphic objects (the so-called virtual table pointer, or vptr) that give the object its run-time identity. In the case of multiple inheritance, several such vptrs can coexist at various offsets inside the object, and most implementations add yet more internal pointers when using virtual inheritance. During normal use, the compiler takes care of managing all of these hidden fields; memcpy can only wreak havoc.

Similarly, memcmp is an inappropriate tool for comparing anything more elaborate than bits. Sometimes, it does too little (e.g., comparing C-style strings is not the same as comparing the pointers with which the strings are implemented). And sometimes, paradoxically, memcmp does too much (e.g., memcmp will needlessly compare bytes that are not part of an object's state, such as padding inserted by the compiler for alignment purposes). In both cases, the comparison's result will be wrong.

    Team LiB
    Previous Section Next Section