簡體   English   中英

shared_ptr 的 use_count() 移入 gcc 4.6.3 中的 std::async

[英]use_count() of shared_ptr moved into a std::async in gcc 4.6.3

在下面的代碼中,我希望將shared_ptruse_count()移入std::async1

#include <memory>
#include <iostream> 
#include <future> 

using namespace std;

void fun(shared_ptr<int> sp)
{
    cout << "fun: sp.use_count() == " << sp.use_count() <<
        " (in gcc 4.6.3, is there a way to make this 1?)\n";
}

int main()
{
    auto sp1 = make_shared<int>(5);

    auto fut = async(
        launch::async,
        fun,
        move(sp1)
    );
}

我的平台使用 gcc 4.6.3,上面的代碼給出了這個輸出( fun: sp.use_count() == 2 ):

fun: sp.use_count() == 2 (in gcc 4.6.3, is there a way to make this 1?)

coliru.stacked-crooked.com 上,我得到了我想要的行為( fun: sp.use_count() == 1 ):

fun: sp.use_count() == 1 (in gcc 4.6.3, is there a way to make this 1?)

我不確定coliru 使用的是什么編譯器,但我猜它比gcc 4.6.3 新。

有沒有辦法,一些變通辦法,來獲得我想要的行為,而不必從 gcc 4.6.3 升級我的編譯器?

一個可能的解決方法可能是

void fun(shared_ptr<int>* sp)
{
    unique_ptr<shared_ptr<int>> guard(sp);

    cout << "fun: sp.use_count() == " << sp->use_count() <<
        " (in gcc 4.6.3, is there a way to make this 1?)\n";
}

int main()
{
    auto sp1 = make_shared<int>(5);

    auto fut = async(
        launch::async,
        fun,
        new shared_ptr<int>(move(sp1))
    );
}

也就是說,看看 gcc463 在原始代碼中在哪里制作額外的副本會很有趣; 似乎 async() 中由decay_copy 給出的臨時值沒有像它應該的那樣作為右值轉發給fun() 的參數。 你不能用你的調試器介入看看發生了什么嗎?

盡管std::async會復制所有參數,但在調用該函數時,它會將參數完美轉發到可調用對象,以便保留參數值類別。

std::async的參數只需要是MoveConstructible ,否則不可能將std::unique_ptr傳遞到std::async

換句話說,正確的行為是sp.use_count() == 1 ,這是我用舊的 g++-5.3.1 觀察到的。


檢查以下代碼是否與您觀察到sp.use_count() == 2的編譯器一起編譯:

using namespace std;

void fun(unique_ptr<int> p) {
    cout << "fun " << *p << '\n';
}

int main() {
    unique_ptr<int> sp(new int{1});

    auto fut = async(
        launch::async,
        fun,
        move(sp)
    );

    fut.get();
}

暫無
暫無

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

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