Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

เมื่อไหร่ควรใช้ inline Keyword ใน C++

inline บอกคอมไพเลอร์ให้แทรกโค้ดฟังก์ชันที่จุดเรียก (inlining) แทนการ call ปกติ

เมื่อควรใช้

  • ฟังก์ชันเล็ก เรียกบ่อย (getters, setters, math helpers)
  • ฟังก์ชันใน header file (หลีกเลี่ยง multiple definition errors)
  • Template functions (implicit inline)
  • Member functions ที่ define ใน class body (implicit inline)

ตัวอย่าง

inline int max(int a, int b) { return a > b ? a : b; }

// ใน class - implicit inline
class MyClass {
    int value;
public:
    int get() const { return value; } // implicit inline
    void set(int v) { value = v; }    // implicit inline
};

ข้อควรระวัง

  • Compiler อาจ ignore inline หากฟังก์ซ์ใหญ่เกินไป
  • เปลี่ยน inline function ต้อง recompile ทุก translation unit ที่ include header
  • Overuse เพิ่ม code size (code bloat) สร้าง instruction cache misses
  • ไม่ inline ได้: recursive functions, virtual functions (ส่วนใหญ่), functions ที่มี static variables

Modern C++

C++17: inline variables, inline namespaces
C++20: consteval, constinit สำหรับ compile-time evaluation