C ++ Advanced three: the type of security and STL

  • Do not handle dynamic arrays

Here there are two meanings:

  1. Ground-based support pointers not be dynamic ++, + n this operation, as it would actually be calculated offset base class size, rather than the expected size of the offset calculated according subclass;

2. pointer reference, and not to make use of the interface, the reason is desirable to clear the surface of an object in question, rather than an array of objects;

  • Do not use invalid objects

Often easy to overlook the failure objects include:

  1. Failure semantic objects: to a deleted object dangling (after the dangling) Pointer
  2. Failure iterator: after, for example, pointed in the iterator container initial insertion vector <T> :: iterator i
  • Do not use insecure legacy C language functions:
    strcpy \ sprintf buffers are not checked range; strncpy \ snprintf although check buffer boundaries, but do not add null buffer limit is reached. So it is unsafe

  • Do not use variable-length parameters (...)
    C ++ variable length parameters drawbacks include:

    1. Lack of type safety. Ellipsis essentially tells the compiler: Close all the checks, since taken over by me, start reinterpret_cast
    2. Caller and callee There is a close coupling;
    3. Behavior type of object class is not defined;
    4. The number of unknown parameters
  • Do not use the Joint reinterpret representation
    such as members of a union member and a long type of a pointer type, the pointer to the assignment, then read their address by long, so there will be a problem:

    1. Different architectures and compilers sizeof (long) may not be equal to sizeof (char *)
    2. Reduces the readability of the code;
  • Do not copy the object using memcpy, do not compare the object with memcmp
    compiler will embed some of the hidden data (so-called virtual function table pointer vptr) in the multi-state object, using virtual inheritance when most compilers implement will add more internal pointer . General use, the compiler is responsible to manage all these hidden data.

Guess you like

Origin blog.51cto.com/xiamachao/2460837