【问题标题】:error C2248: 'std::promise<_Ty>::promise' : cannot access private member declared in class 'std::promise<_Ty>'错误 C2248:“std::promise<_Ty>::promise”:无法访问在类“std::promise<_Ty>”中声明的私有成员
【发布时间】:2015-02-24 22:37:03
【问题描述】:

如何更正以下代码以避免出现错误消息? 这段代码不应该工作吗? 是否可以使用不同的技术(packaged_task、asynch)?

#include <list>
#include <future>

using namespace std;

template<typename T>
struct sorter
{
    struct chunk_to_sort
    {
        std::list<T> data_m;
        std::promise<std::list<T> > promise_m;
    };
    list<chunk_to_sort> chunks_m;
    void do_sort(std::list<T>& chunk_data)
    {
        std::list<T> result;
        result.splice(result.begin(),chunk_data,chunk_data.begin());
        T const& partition_val=*result.begin();
        typename std::list<T>::iterator divide_point = std::partition(chunk_data.begin(),chunk_data.end(),[&](T const& val){return val<partition_val;});
        chunk_to_sort new_lower_chunk;
        new_lower_chunk.data_m.splice(new_lower_chunk.data_m.end(), chunk_data,chunk_data.begin(),divide_point);
        chunks_m.emplace_back(std::move(new_lower_chunk));
    }
};

int main()
{
    sorter<int> s;
    list<int> l;
    l.push_back(4);
    l.push_back(3);
    s.do_sort(l);
    return 0;
}

【问题讨论】:

  • 已在 Visual Studio 2015 CTP6 中修复

标签: c++ multithreading c++11 promise future


【解决方案1】:

您在 gcc 和 clang 上的代码 compiles successfully(一旦包含缺少的 &lt;algorithm&gt; 标头)。由于这条线,它在 MSVC 上失败

chunks_m.emplace_back(std::move(new_lower_chunk));

问题在于 VS2013 和更早的 do not implicitly generate a move constructor,因此 emplace_back 调用最终会尝试复制构造一个格式错误的 chunk_to_sort,因为 std::promise 是只能移动的。

为了解决这个问题,提供一个移动构造函数定义(也可能是一个移动赋值运算符定义)。

chunk_to_sort() = default;

chunk_to_sort(chunk_to_sort&& other)
: data_m(std::move(other.data_m))
, promise_m(std::move(other.promise_m))
{}

【讨论】:

  • 谢谢,这确实很清楚
  • 我需要学习如何接受一个问题,很快就会接受你的。我是这个论坛的新手。
猜你喜欢
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
相关资源
最近更新 更多