Examples
Team LiB
Previous Section Next Section

Examples

Example: Using std::string in a module interface. Say a module wants to provide this API:



std::string Translate( const std::string& );



For libraries used internally in one team or company, this is usually fine. But if you need to dynamically link this module together with a caller that has a different implementation of std::string (sporting a different memory layout), strange things will happen because the client and the module can't understand each others' strings.

We have seen developers try to get around this by wrapping std::string with their own CustomString, only to be shocked when they continue to encounter the very same problem because they don't control the build process of all callers.

One solution is to rely on portable (probably built-in) types, either instead of or in addition to the function that takes a string. For example:



void Translate( const char* src, char* dest, size_t destSize );



Using a lower-level abstraction is more portable, but always adds complexity; e.g., here, both the caller and the callee have to explicitly deal with possible truncation if the buffer is not big enough. (Note that this version uses a caller-allocated buffer to avoid the pitfall of allocating and deallocating memory in different modules; see Item 60.)

    Team LiB
    Previous Section Next Section