用C++11的std::unique_ptr取代C++98中老旧的std::auto_ptr
由于MSVC编译器在C++17中顺应标准,将老旧的 std::auto_ptr
完全移除了。因此我们只能用C++11起新引入的 std::unique_ptr
来取代。不过好在这两个类一些常用的基本接口、包括接口名都没有换,而且语义也保持一致。因此我们通常情况下直接可实现无缝替换。
std::unique_ptr
和 std::auto_ptr
一般常用的方法有:get
、reset
和 release
。下面我们用比较简短的代码样例来描述这两者的等价替换性。
#include <cstdio>
#include <memory>int main()
{struct MyObject{int m_value = 0;MyObject() { puts("MyObject has been created!!"); }MyObject(int i): m_value(i) { printf("MyObject with %d has been created!!", m_value); }~MyObject() { printf("MyObject with %d has been destroyed!!\\n", m_value); }};auto auto_ptr_test = [](int i) {std::auto_ptr<MyObject> autoPtrObj(nullptr);autoPtrObj.reset(new MyObject(i));MyObject* objPtr = autoPtrObj.get();printf("The value is: %d\\n", objPtr->m_value);};auto_ptr_test(10);auto_ptr_test(20);auto unique_ptr_test = [](int i) {std::unique_ptr<MyObject> uniquePtrObj(nullptr);uniquePtrObj.reset(new MyObject(i));MyObject* objPtr = uniquePtrObj.get();printf("The value is: %d\\n", objPtr->m_value);};unique_ptr_test(100);unique_ptr_test(200);
}
各位倘若是用MSVC来尝试编译上述代码的话,则不能使用C++17或更新C++标准,而只能使用C++11或C++14进行编译。
进阶参考
- C++11使用std::make_unique避免数据成员默认清零
- C++11释放std::unique_ptr的所有权,获得其原始指针