C++11新特性(四)static_assert, share_ptr, unique_ptr簡單使用



// auto also as the type of turn, as long as appoint the type

#include <iostream>

auto add(int a, int b)->int

{

    return a + b;

}

int main()

{

    

    static_assert(444 < 9000, "too bigger");

    

    auto result = add(1000, 200);

    std::cout << result << std::endl;

    

    

    /*Section of the shared_ptr*/

    

    std::shared_ptr<int> ptr(new int(100));

    std::cout << *ptr << std::endl;

    

    std::shared_ptr<int> other = ptr;

    *other = 200;

    std::cout << *ptr << std::endl;

    

    auto value = std::make_shared<int>(300);

    std::cout << *value << std::endl;

    

    /*Section of the unique_ptr*/

    

    std::unique_ptr<int> pn1(new int(2));

    std::unique_ptr<int> pn2 = std::move(pn1); // transfer ownership

    if (!pn1) {

        std::cout << "It is null" << std::endl;

    }

    

    

    /*Section of the weak_ptr*/


    auto p = std::make_shared<int>(33);

    std::weak_ptr<int> wp = p;

    

    {

        auto sp = wp.lock();

        std::cout << *sp << std::endl;

    }

    

    p.reset();

    

    if(wp.expired())

        std::cout << "expired" << std::endl;

    return 0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章