Effective C++ - Item2

박영재·2024년 9월 25일

Depend on a Compiler Rather than a Preprocessor

Replacing #define Values with const

Since a compiler does not include macro names in its symbol table, values defined by #define are not associated with symbols during compile time.

Cautions

  1. Constant Pointers:

    When defining a constant pointer, both the pointer and the value it points to must be const.

    
    const char* const NAME = "Aiden";
    
  2. Static const in Classes:

    A static const member is declared inside the class and defined outside it.

    
    class A {
    private:
        static const std::string NAME; // declared
    };
    
    const std::string A::NAME = "Aiden"; // defined
    
  3. Enum Hack:

    If a constant value is required during compilation, the enum hack can be a solution. It behaves more like a #define than a const.

Replacing Macro Procedures with Inline and Template Functions

Macros are often used to define reusable code blocks, but they can introduce issues like lack of type safety, unexpected side effects, and difficulty in debugging. A better alternative is to use inline functions and templates, which provide type safety, maintain readability, and are optimized by the compiler.

Inline Functions

inline functions allow a programmer to define small functions that the compiler will attempt to expand in place where they are used, avoiding the overhead of a function call.

Unlike macros, this function prevents issues like double evaluation of expressions, which is common in macros.

Template Functions

Templates provide an even more flexible and powerful way to replace macros, allowing a programmer to write functions that work with different types.

By using inline and template functions, a programmer benefits from compile-time checks, better debugging support, and improved code clarity, while still maintaining the performance benefits of macros.

Example:

#define MAX(a, b) ((a) > (b) ? (a) : (b))  // Macro// Replace with a template function
template <typename T>
inline T max(T a, T b) {
    return (a > b) ? a : b;
}
profile
People live above layers of abstraction beneath which engineers reside

0개의 댓글