在C ++中make_unique和带有reference_wrapper的make_unique之间的区别

时间:2019-03-28 11:04:45

标签: c++ c++11 c++14

struct Foo{};

std::make_unique<Foo>std::make_unique<std::reference_wrapper<Foo>>有什么区别?

3 个答案:

答案 0 :(得分:2)

std::make_unique<Foo>

返回

std::unique_ptr<Foo>


std::make_unique<std::reference_wrapper<Foo>>

返回

std::unique_ptr<std::reference_wrapper<Foo>>


std::reference_wrapper是普通指针上的非所有者包装。导致std::unique_ptr拥有std::reference_wrapper<Foo>,而该实体不拥有它所指的Foo

std::unique_ptr<std::reference_wrapper<Foo>>等效于std::unque_ptr<Foo*>,其中Foo*被销毁,而Foo被销毁。随之而来的是很容易引入内存泄漏,从而破坏了std::unique_ptr的目的。

答案 1 :(得分:2)

Foo根据传递的所有参数创建一个具有动态存储持续时间的std::make_unique<Foo>(args...)。当且仅当Foo(args...)也有效时,std::make_unique<std::reference_wrapper<Foo>>是有效的表达式。

std::reference_wrapper<Foo>使用另一个std::reference_wrapper<Foo>或将绑定到Foo &但不绑定Foo &&的东西创建一个具有动态存储持续时间的Foo。它不会创建任何其他Foo,您需要至少一个std::unique_ptr<std::reference_wrapper<Foo>>才能存在。

我想不出有充分的理由在gsl::observer<Foo>(又名Foo *),std::reference_wrapper<Foo>std::unique_ptr<Foo>上使用 private void InsertByDapper(string className, SqlConnection conn) { Type type = Type.GetType(className); if (type != null) { var instance = Activator.CreateInstance(type); // ... update some properties in the instance object... conn.Insert(instance); //connTo.Insert((ClassName)instance); //This statment works } } ,具体取决于你想做什么。

答案 2 :(得分:1)

std::make_unique<std::reference_wrapper<Foo>>返回一个拥有的智能指针,该指针指向对Foo的引用。

Foo的引用是在堆上分配的。

从未创建实际的Foo

出于同样的原因,它将无法编译:

auto x = std::make_unique<std::reference_wrapper<Foo>>();

结果:

error: 'std::reference_wrapper<Foo>': no appropriate default constructor available

使其生效的唯一方法是使它引用一些预先存在的Foo

Foo foo;
auto x = std::make_unique<std::reference_wrapper<Foo>>(foo);

无法想到一个有效的用例。

相关问题