」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 當你的編譯器不支援時,如何在 C++11 實作 `make_unique`?

當你的編譯器不支援時,如何在 C++11 實作 `make_unique`?

發佈於2024-11-08
瀏覽:368

How to Implement `make_unique` in C  11 When Your Compiler Doesn\'t Support It?

在 C 11 中重新建立 make_unique 函數

C 11 標準引入了一個強大的函數 make_unique,用於建立唯一指標。然而,有些人可能會遇到編譯器不支援此功能的問題。本文提供了在 C 11 中實作 make_unique 的解決方法。

根據問題,make_unique 函數原型為:

template unique_ptr make_unique( Args&&&... args );

以下程式碼提供了make_unique的實作:

template
std::unique_ptr make_unique(Args&&... args)
{
    return std::unique_ptr(new T(std::forward(args)...));
}

此實作使用 std::forward 函數來確保所有類型的參數(包括引用和右值引用)都能正確進行參數轉送。

請注意,如果您的編譯器支援 C 11 但不是 make_unique 函數,您仍然可以使用此實作作為解決方法。或者,如果您有權存取支援 C 14 或更高版本的編譯器,則可以簡單地利用標準 std::make_unique 函數來實現此目的。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3