C语言编程(基于GNU语法扩展)

用C++11的std::unique_ptr取代C++98中老旧

2023-01-30  本文已影响0人  zenny_chen

由于MSVC编译器在C++17中顺应标准,将老旧的 std::auto_ptr
完全移除了。因此我们只能用C++11起新引入的 std::unique_ptr
来取代。不过好在这两个类一些常用的基本接口、包括接口名都没有换,而且语义也保持一致。因此我们通常情况下直接可做无缝替换。

std::unique_ptrstd::auto_ptr 一般常用的方法有:getresetrelease。下面我们用比较简短的代码样例来描述这两者的等价替换性。

#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 const& 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 const& 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进行编译。

上一篇 下一篇

猜你喜欢

热点阅读