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

เมื่อไหร่ควรใช้ new Operator ใน C++ และเมื่อไหร่ไม่ควรใช้

ภาพรวม

new Operator ใน C++ ใช้สำหรับ Dynamic Memory Allocation บน Heap คืนค่า Pointer ชี้ไปที่หน่วยความจำที่จองไว้ ต้องจับคู่กับ delete เพื่อปล่อยหน่วยความจำ

Syntax


// Single object
Type* ptr = new Type;           // Default initialize
Type* ptr = new Type();         // Value initialize (zero)
Type* ptr = new Type(value);    // Direct initialize

// Array
Type* ptr = new Type[n];        // Array of n objects

เมื่อไหร่ควรใช้ new

  • Object ต้องมีอายุชีวิตเกิน Scope: ต้องใช้งานต่อหลังฟังก์ชันจบ
  • ขนาดไม่ทราบ Compile-time: ขนาด Array กำหนดได้ตอน Runtime
  • Polymorphism: Base Class Pointer ชี้ Derived Object
  • Large Objects: หลีกเลี่ยง Stack Overflow (Stack จำกัด ~1-8MB)
  • Shared Ownership: หลายส่วนเข้าถึงออบเจ็กต์เดียวกัน (ใช้ shared_ptr)
  • Custom Allocator: จัดการหน่วยความจำเฉพาะทาง

เมื่อไหร่ไม่ควรใช้ new (ใช้ Automatic Storage แทน)

  • Object ใช้งานเฉพาะใน Scope ปัจจุบัน: ให้ประกาศเป็น Local Variable
  • ขนาดเล็ก และทราบขนาด Compile-time: ใช้ Stack (เร็วกว่า, Auto Cleanup)
  • ไม่ต้องการ Polymorphism: ใช้ Value Semantics
  • RAII Containers: ใช้ std::vector, std::string, std::array แทน Raw Array
  • Modern C++: ใช้ Smart Pointers (unique_ptr, shared_ptr) แทน Raw new

ตัวอย่างโค้ด

#include <iostream>
#include <memory>  // Smart Pointers
using namespace std;

class Resource {
public:
    Resource(int id) : id_(id) { cout << "Resource " << id_ << " acquired\n"; }
    ~Resource() { cout << "Resource " << id_ << " released\n"; }
    void use() { cout << "Using resource " << id_ << "\n"; }
private:
    int id_;
};

int main() {
    // ❌ ไม่ควร: Manual new/delete - Risky
    Resource* raw = new Resource(1);
    raw->use();
    delete raw;  // ถ้า Exception ระหว่างทาง -> Leak!
    
    // ✅ ควร: Unique Pointer (Single Ownership)
    auto unique = make_unique<Resource>(2);
    unique->use();
    // Auto delete เมื่อออก Scope
    
    // ✅ ควร: Shared Pointer (Shared Ownership)
    auto shared1 = make_shared<Resource>(3);
    auto shared2 = shared1;  // Share ownership
    shared1->use();
    // Auto delete เมื่อ Reference Count = 0
    
    // ✅ ควร: Stack Allocation (Simple Cases)
    Resource local(4);
    local.use();
    // Auto destroy เมื่อออก Scope
    
    return 0;
}

ผลลัพธ์

Resource 1 acquired
Using resource 1
Resource 1 released
Resource 2 acquired
Using resource 2
Resource 2 released
Resource 3 acquired
Using resource 3
Resource 4 acquired
Using resource 4
Resource 3 released
Resource 4 released

Best Practices สรุป

  1. Default Choice: Stack Allocation (Local Variables)
  2. Dynamic Size/Shared: std::vector, std::string, Containers
  3. Polymorphism/Heap Needed: std::make_unique / std::make_shared
  4. Never: Raw new/delete ใน Modern C++ (Exception Safety, Leak Risk)
  5. Rule of Zero: ให้ Compiler/Containers จัดการ Memory ให้

ข้อผิดพลาดที่พบบ่อย

  • ลืม delete → Memory Leak
  • delete แทน delete[] สำหรับ Array → Undefined Behavior
  • Double Delete → Crash/Corruption
  • Use After Delete → Dangling Pointer
  • Exception ระหว่าง new/delete → Leak (แก้ด้วย Smart Pointers)