簡體   English   中英

移入unique_ptr容器

[英]moving into unique_ptr container

我要執行的操作與cppreference.com上的unique_ptr的代碼段極為相似。 摘錄如下。 它編譯良好。

#include <iostream>
#include <list>
#include <vector>
#include <string>
#include <iterator>

int main()
{
    std::list<std::string> s{"one", "two", "three"};

    std::vector<std::string> v1(s.begin(), s.end()); // copy

    std::vector<std::string> v2(std::make_move_iterator(s.begin()),
                                std::make_move_iterator(s.end())); // move

    std::cout << "v1 now holds: ";
    for (auto str : v1)
            std::cout << "\"" << str << "\" ";
    std::cout << "\nv2 now holds: ";
    for (auto str : v2)
            std::cout << "\"" << str << "\" ";
    std::cout << "\noriginal list now holds: ";
    for (auto str : s)
            std::cout << "\"" << str << "\" ";
    std::cout << '\n';
}

我真正想要的是將字符串從s移到unique_ptr向量中

所以像std::vector<std::unique_ptr<std::string>> v2(&std::make_move_iterator(s.begin()), &std::make_move_iterator(s.end()));

但這當然行不通。

我只能用這段代碼來做我想做的事情:

int main()
{
    std::list<std::string> s{"one", "two", "three"};

    std::vector<std::string> v1(s.begin(), s.end()); // copy

    std::vector<std::unique_ptr<std::string>> v2;
    for(auto& o : s)
    {
        std::unique_ptr<std::string> p ( new std::string(move(o)));
        v2.push_back(move(p));
    }

    std::cout << "\nv2 now holds: ";
    for (auto& pstr : v2)
            std::cout << "\"" << *pstr << "\" ";
    std::cout << "\noriginal list now holds: ";
    for (auto str : s)
            std::cout << "\"" << str << "\" ";
    std::cout << '\n';
} 

有沒有一種方法可以將資源移動到一行中的unique_ptrs容器中?

是的,如果您按照Herb Sutter的建議使用make_unique函數,則可以執行以下操作:

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
    return std::unique_ptr<T> ( new T( std::forward<Args>(args)... ) );
}

int main()
{
    std::list<std::string> s{"one", "two", "three"};

    std::vector<std::unique_ptr<std::string>> v2;
    std::transform(begin(s), end(s), std::back_inserter(v2),
            &make_unique<std::string, std::string&>
    );
}

我已經從Herbs頁面上取消了make_unique ,它已包含在C ++ 14中或僅使用此版本。

http://herbsutter.com/gotw/_102/

不幸的是,我們不能使用類型推導,因此我們必須手動提供類型。

暫無
暫無

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

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