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

วิธี Return Local Array จากฟังก์ชัน C++

ภาพรวม

ใน C++ ไม่สามารถ Return Local Array ได้โดยตรง เพราะ Local Array อยู่บน Stack จะถูกทำลายเมื่อฟังก์ชันจบ ทำให้ Pointer ที่ Return ไปชี้หน่วยความจำที่ไม่ถูกต้อง (Dangling Pointer) → Undefined Behavior

วิธีแก้ไข (3 วิธีหลัก)

1. ใช้ Static Local Array (Simple แต่มีข้อจำกัด)


#include <iostream>
using namespace std;

int* retArray() {
    static int arr[10];  // Static Storage Duration - ไม่ถูกทำลาย
    for (int i = 0; i < 10; i++) {
        arr[i] = i + 1;
    }
    return arr;  // Safe: arr ยังอยู่หลังฟังก์ชันจบ
}

int main() {
    int* ptr = retArray();
    cout << "The array elements are: ";
    for (int i = 0; i < 10; i++) {
        cout << ptr[i] << " ";
    }
    return 0;
}

2. ใช้ Dynamic Allocation (new) - Caller ต้อง Delete


int* createArray(int size) {
    int* arr = new int[size];  // Heap Allocation
    for (int i = 0; i < size; i++) arr[i] = i + 1;
    return arr;  // Caller ต้อง delete[] นี้!
}

int main() {
    int* arr = createArray(10);
    // ใช้งาน...
    delete[] arr;  // จำเป็นต้อง Free เอง
    return 0;
}

3. ใช้ std::vector / std::array (Modern C++ - แนะนำสุด)


#include <vector>
#include <array>

// Fixed size - ใช้ std::array
array<int, 10> createFixedArray() {
    array<int, 10> arr;
    for (int i = 0; i < 10; i++) arr[i] = i + 1;
    return arr;  // Return by Value (Copy/Move) - Safe!
}

// Dynamic size - ใช้ std::vector
vector<int> createDynamicArray(int size) {
    vector<int> vec(size);
    for (int i = 0; i < size; i++) vec[i] = i + 1;
    return vec;  // NRVO/RVO Optimized - No Copy!
}

ผลลัพธ์ตัวอย่าง (Static Array)

The array elements are: 1 2 3 4 5 6 7 8 9 10

การเปรียบเทียบวิธีต่างๆ

วิธีความปลอดภัยMemory Mgmtข้อจำกัดแนะนำ
Static Local ArrayปลอดภัยAutoFixed Size, Shared State, Not Thread-safe⚠️ Limited Use
new/deleteManualManualMemory Leak Risk, Exception Unsafe❌ Avoid
std::vector✅ ปลอดภัยAuto (RAII)Dynamic Size, Flexible✅ Best
std::array✅ ปลอดภัยAuto (Stack)Fixed Size (Compile-time)✅ Best (Fixed)
std::span (C++20)✅ ปลอดภัยNon-owningView Only✅ Modern

ข้อสังเกตสำคัญ

  • Static Array แชร์ข้อมูลระหว่างการเรียกทุกครั้ง (Shared State)
  • C++17+ มี Guaranteed Copy Elision (NRVO) ทำให้ Return by Value ไม่มี Overhead
  • หลีกเลี่ยง Raw Pointer Ownership Transfer ใช้ Smart Pointers หรือ Containers แทน