Std::make_shared, Std::unique_ptr和move构造函数
std::make_shared, std::unique_ptr and move constructors
使用clang 3.0/libc++编译以下代码:
#include <memory>
class Foo
{
public:
Foo()
: mem_(new int(10))
{
}
std::unique_ptr<int> mem_;
};
int main()
{
auto foo = std::make_shared<Foo>();
return 0;
}
但是这个没有(添加了std::string
参数):
#include <memory>
#include <string>
class Foo
{
public:
Foo(const std::string& s)
: mem_(new int(10))
{
}
std::unique_ptr<int> mem_;
};
int main()
{
auto foo = std::make_shared<Foo>("aaa");
return 0;
}
Clang抱怨使用了已删除的构造函数。对我来说,这没有意义,因为std::make_shared
不应该复制Foo实例,这是唯一会触发对std::unique_ptr
的(已删除的)复制构造函数的调用的事情。
但是你瞧,只要我显式地定义了一个move构造函数,它就会编译。
#include <memory>
#include <string>
class Foo
{
public:
Foo(const std::string& s)
: mem_(new int(10))
{
}
Foo(Foo&& other)
: mem_(std::move(other.mem_))
{
}
std::unique_ptr<int> mem_;
};
int main()
{
auto foo = std::make_shared<Foo>("aaa");
return 0;
}
现在,问题:
- 为什么它在第一个例子中编译而不是第二个例子?
-
std::make_shared
在构建对象时可以复制/移动对象吗? - 为什么添加一个移动构造器修复这个问题?我不记得添加非默认构造函数应该抑制隐式move构造函数。
编辑:检查和所有的例子似乎与gcc 4.5.1编译良好(通过ideone.com),我怀疑这是clang/libc++错误的情况下,但问题2和3仍然存在,加上我想知道哪个编译器更"正确"。
为什么在第一个例子中可以编译,而在第二个例子中不能?
这是一个libc++错误。我正在努力解决这个问题…
std::make_shared可以在构造对象时复制/移动对象吗?
不,我不相信它可以。
为什么添加move构造函数可以解决这个问题?我不记得了添加非默认构造函数应该抑制隐式移动构造函数。
在你使用的clang版本中,隐式move构造函数还没有实现。
固定:http://llvm.org/bugs/show_bug.cgi?id=11616
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 初始化具有非默认构造函数的std::数组项的更好方法
- 编译器如何区分std::vector的构造函数
- 为什么std::vector和std::valarray初始化构造函数不同
- std::make_shared和protected/private构造函数
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- std::ofstream 作为类成员删除复制构造函数?
- std::string 构造函数如何处理固定大小的 char[]?
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 在构造函数中使用可变参数初始化 std::tuple
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 如何在构造函数参数中初始化"std::set"?
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 创建一个没有复制构造函数的类的 std::vector 的 std::vector
- 构造函数采用std::string_view与std::string并移动
- C++ - std::构造函数中的矢量初始化
- 关于 std::bitset 构造函数的几个问题?
- 对 std 构造函数的调用是否需要限定