仅叮当:一对<路径,路径>可以放入向量中;一对也可以<unique_ptr,unique_ptr>;但不能成对<路径,unique_ptr>:为什么?

Clang only: A pair<path, path> can be emplaced into a vector; so can a pair<unique_ptr, unique_ptr>; but NOT pair<path, unique_ptr>: Why?

本文关键字:gt ptr unique 路径 lt 也可以 但不能 为什么 一对 叮当 向量      更新时间:2023-10-16

我有以下三段代码来演示一个易于复制的问题。

using namespace boost::filesystem;
using namespace std;
int main()
{
    path dummy_path;
    // Snippet 1
    // Two paths
    // Succeeds
    //
    // vector<pair<path, path>> myvec;
    // myvec.emplace_back(dummy_path, dummy_path);
    // Snippet 2
    // Two unique_ptr's
    // Succeeds
    //
    // vector<pair<unique_ptr<int>, unique_ptr<int>>> myvec;
    // myvec.emplace_back(unique_ptr<int>(new int(13)), unique_ptr<int>(new int(12)));
    // Snippet 3
    // A path and a unique_ptr.
    //
    // **FAILS** on Clang, succeeds in Visual Studio
    //
    vector<pair<path, unique_ptr<int>>> myvec;
    myvec.emplace_back(dummy_path, unique_ptr<int>(new int(12)));
}

以下是Clang:上的编译器错误

error: call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<int, std::__1::default_delete<int> >'(显然是指该对中的第二个成员unique_ptr)。

似乎由于某种原因,指示的失败情况导致调用了对的复制构造函数,而不是移动构造函数。

这是OS X 10.8.5上的Clang 5.0.2。(以及VS 11.0.60610.01 Windows 7 64位更新3。)

在我的实际应用程序中,数据类型更复杂,但错误可以归结为本问题中描述的错误。

我的问题有两个:为什么Clang上指示的案例失败了,尽管其他两个案例(涵盖了这两种数据类型)都成功了?

然而,也许更重要的是:我能做些什么来解决这个问题因为我的实际应用程序更复杂,所以我不能选择不将给定对放置到向量中(或其他等效的东西),但如果有其他方法可以解决Clang问题,将该对放置到该向量中,我会非常高兴。

很抱歉,这是libc++中的一个错误。它已经固定在树干的顶端。我相信你可以通过在编译命令中添加以下内容来解决这个问题:

-D_LIBCPP_TRIVIAL_PAIR_COPY_CTOR

问题来自libc++标准库,因为它中的pair构造函数要少得多。

即libstd++有以下构造函数:

template<class _U2, class = typename
       enable_if<is_convertible<_U2, _T2>::value>::type>
constexpr pair(const _T1& __x, _U2&& __y)
: first(__x), second(std::forward<_U2>(__y)) { }

这允许在Linux上编译您的示例(使用clang++)。但libc++只有:

pair(const pair&) = default;
pair(pair&&) = default;
constexpr pair();
pair(const T1& x, const T2& y);                          // constexpr in C++14
template <class U, class V> pair(U&& x, V&& y);          // constexpr in C++14
template <class U, class V> pair(const pair<U, V>& p);   // constexpr in C++14
template <class U, class V> pair(pair<U, V>&& p);        // constexpr in C++14
template <class... Args1, class... Args2>
    pair(piecewise_construct_t, tuple<Args1...> first_args,
         tuple<Args2...> second_args);

我想,由于第一个参数是非右值引用,所以应用了pair(const T1& x, const T2& y);


"核心"解决方案是将这个构造函数手动放置在系统库中。pairutility文件中定义。如果你想在其他地方编译你的代码,你可以把修改后的libc++捆绑到你的项目中——这真的没什么大不了的。