簡體   English   中英

unique_ptr提升等價?

[英]unique_ptr boost equivalent?

在boost庫中是否有一些與C ++ 1x的std :: unique_ptr等效的類? 我正在尋找的行為是能夠擁有異常安全的工廠功能,就像這樣......

std::unique_ptr<Base> create_base()
{
    return std::unique_ptr<Base>(new Derived);
}

void some_other_function()
{
    std::unique_ptr<Base> b = create_base();

    // Do some stuff with b that may or may not throw an exception...

    // Now b is destructed automagically.
}

編輯:現在,我正在使用這個黑客,這似乎是我能在這一點上得到的最好的......

Base* create_base()
{
    return new Derived;
}

void some_other_function()
{
    boost::scoped_ptr<Base> b = create_base();

    // Do some stuff with b that may or may not throw an exception...

    // Now b is deleted automagically.
}

在沒有C ++ 0x的情況下創建類似unique_ptr東西是不可能的(它是標准庫的一部分,因此Boost不需要提供它)。

特別是沒有rvalue引用(這是C ++ 0x中的一個特性),無論是否有Boost,都不可能實現unique_ptr的強大實現。

在C ++ 03中,有一些可能的替代方案,盡管每個都有它們的缺陷。

  • boost::shared_ptr可能是功能方面最簡單的替代品。 你可以安全地在任何你使用unique_ptr地方使用它,它可以工作。 由於添加了引用計數,它不會那么高效。 但是如果你正在尋找一個能夠處理unique_ptr可以做的所有事情的簡單替代品,這可能是你最好的選擇。 (當然, shared_ptr也可以做得更多,但它也可以簡單地用作unique_ptr替代品。)
  • boost::scoped_ptr類似於unique_ptr但不允許轉讓所有權。 只要智能指針在其整個生命周期中保留獨占所有權,它就能很好地工作。
  • std::auto_ptrunique_ptr非常相似,但有一些限制,主要是它不能存儲在標准庫容器中。 如果您只是尋找一個允許轉讓所有權的指針,但這並不意味着存儲在容器中或復制,這可能是一個不錯的選擇。

Boost 1.57開始, Boost.Move庫中有一個官方的unique_ptr實現。

文檔

(...)std :: unique_ptr的替代品,也可以從C ++ 03編譯器中使用。

該代碼在<boost/move/unique_ptr.hpp>頭文件中可用,並且位於boost::movelib命名空間中。 此外,Boost.Move庫在<boost/move/make_unique.hpp>提供了make_unique()工廠函數,也在boost::movelib命名空間中。

因此,問題的例子可以這樣實現:

#include <boost/move/unique_ptr.hpp>

using boost::movelib::unique_ptr;

unique_ptr<Base> create_base()
{
    return unique_ptr<Base>(new Derived);
}

查看Wandbox上的實例 請注意,代碼在C ++ 98模式(!)中使用gcc 4.6.4編譯得很好。

boost::movelib::unique_ptr在應用於具有基類/派生類的情況時有什么boost::movelib::unique_ptr ,該實現提供了對基類中虛擬析構函數聲明的編譯時檢查。 如果您碰巧省略它,代碼將無法編譯 (單擊“運行(...)”按鈕以查看編譯器錯誤消息)。

一個小問題是包括來自boost/move目錄,但代碼存在於boost::movelib命名空間中(細微差別,但可能很煩人)。

有關更多詳細信息,另請參閱boost郵件列表中的線程

感謝IonGaztañaga這個絕對獨特且有用的代碼。

你可能想嘗試一下Howard Hinnant的'概念證明' unique_ptr<> C ++ 03的實現(免責聲明 - 我沒有):

他的一個例子是返回unique_ptr<int>

unique_ptr<int> factory(int i)
{
    return unique_ptr<int>(new int(i));
}

進程間庫中的unique_ptr怎么樣?

我用過Howard Hinnant的unique_ptr 如果你不擅長從編譯器中讀取瘋狂的元編程錯誤,你可能想要明確指出。 然而,在90%的情況下它確實像unique_ptr一樣。

否則我建議將paramters作為boost::scoped_ptr&和內部交換來竊取所有權。 要獲取unique_ptr樣式返回值,請使用auto_ptr 捕獲shared_ptrscoped_ptrauto_ptr返回值以避免直接使用auto_ptr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM