ERROR: shared_ptr does not name a type
截圖顯示代碼中直接使用 shared_ptr 但編譯器不認識。
shared_ptr 定義在 <memory> (C++11 標準庫) 或 <boost/shared_ptr.hpp> (Boost 庫)。未 #include 導致編譯器不知其類型。std::shared_ptr 從 **C++11** 引入。若編譯器默認 C++98/03(如 VS2010、GCC 4.3 以下),需顯式開啟 C++11 支持(-std=c++11、/std:c++11),或升級編譯器版本。std::shared_ptr 或 using namespace std;(不推薦全局 using)。#include <memory> // 必須包含
// 使用
std::shared_ptr<MyClass> ptr = std::make_shared<MyClass>(args...);
// 或
std::shared_ptr<MyClass> ptr(new MyClass(args...)); // C++11 無 make_shared 時
編譯選項:
GCC/Clang: -std=c++11 (或 c++14/17/20)
MSVC (VS2015+): 默認支持,舊版項目屬性 → C/C++ → Language → C++ Language Standard → /std:c++14 等。
#include <boost/shared_ptr.hpp>
// 使用
boost::shared_ptr<MyClass> ptr(new MyClass(args...));
// 或工廠函數
boost::shared_ptr<MyClass> ptr = boost::make_shared<MyClass>(args...); // Boost 1.53+
需鏈接 Boost 庫(僅頭文件庫則無需鏈接),適配 C++03 環境。
std::shared_ptr + std::make_shared,性能最優、無外部依賴。new,優先 make_shared(單次分配控制塊+對象,異常安全)。std:: 和 boost:: 智能指針,統一標準避免轉換麻煩。補上 #include <memory> 並確保編啟用 C++11+,即可解決 shared_ptr does not name a type 錯誤。