仅叮当:一对<路径,路径>可以放入向量中;一对也可以<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?
我有以下三段代码来演示一个易于复制的问题。
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);
。
"核心"解决方案是将这个构造函数手动放置在系统库中。pair
在utility
文件中定义。如果你想在其他地方编译你的代码,你可以把修改后的libc++捆绑到你的项目中——这真的没什么大不了的。
- CLANG 编译器 说:变量"PTR"可能未初始化
- EASTL矢量<向量<int>>连续的
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 这是MSVC 2013中具有共享PTR的单例的正确实现吗?
- 对唯一 ptr 无效读取的引用向量
- C++ 类型转换基础 PTR 到派生 PTR 保存在引用类中
- 如何使用非类型参数传递模板化类的 Ref 或 Ptr