简体   繁体   English

C++ 入门 5 版:shared_ptr 从 uniqe_ptr 初始化?

[英]C++ primer 5 edition: shared_ptr initialized from uniqe_ptr?

On C++ primer 5 edition.关于 C++ 入门 5 版。 Chapter 12. Dynamic memory: It is written:第 12 章动态 memory: 写成:

shared_ptr p(u); shared_ptr p(u); P assumes ownership from the uniqe_ptr u ; P 取得uniqe_ptr u的所有权; makes u null.使您成为u shared_ptr p(q, d) Assumes ownership for the object to which the built-in pointer q points. shared_ptr p(q, d) 假定内置指针q指向的 object 的所有权。 q must be convertible to T* ($4.11.2, p.161). q必须可转换为T* ($4.11.2,第 161 页)。 p will use the callable object d ($10.3.2, p.388) in place of delete to free q . p将使用可调用的 object d ($10.3.2, p.388) 代替delete to free q

  • I didn't understand "Assumes ownership from the unque_ptr and for the object to which the built-in...".我不明白“假设所有权来自unque_ptr和内置的 object...”。

Can someone explain to me this paragraph?有人可以向我解释这一段吗? Thanks so much.非常感谢。

The book is not clear with types.这本书的类型不清楚。 you need an rvalue ref to construct a shared_ptr from unique_ptr :您需要一个右值 ref 来从unique_ptr 构造一个shared_ptr

 template< class Y, class Deleter > shared_ptr( std::unique_ptr<Y,Deleter>&& r );

check this code:检查此代码:

unique_ptr<int> up{new int{10}};
shared_ptr<int> sp(move(up));
cout << *sp <<'\n';
//cout << *up <<'\n'; // up is nullptr

Live ob Godbolt Live ob Godbolt


smart pointers manage the lifetime of raw pointer they own.智能指针管理它们拥有的原始指针的生命周期。 unique_ptr doesn't share ownership while shared_ptr does. unique_ptr不共享所有权,而shared_ptr共享。 When you construct a shared_ptr from a unique_ptr you have to give up its ownership via move, and unique_ptr cannot be copied.当你从一个unique_ptr构造一个shared_ptr时,你必须通过 move 放弃它的所有权,并且unique_ptr不能被复制。

I think by using "assumes ownership" the author wants to state that, bad things can still happen if you somehow modify the pointer owned by smart pointers.我认为通过使用“假设所有权”,作者想要 state ,如果您以某种方式修改智能指针拥有的指针,仍然会发生坏事。

Smart pointers 'own' (or, perhaps better, 'manage') an underlying raw pointer or object.智能指针“拥有”(或者,也许更好的是,“管理”)底层原始指针或 object。

unique_ptr owns the pointer outright and will delete it when it goes out of scope. unique_ptr完全拥有指针,并在它超出 scope 时将其删除。 shared_ptr potentially shares ownership with other shared_ptr s, and the managed object will be deleted when the last shared_ptr goes out of scope. shared_ptr可能与其他shared_ptr共享所有权,并且当最后一个shared_ptr离开 scope 时,将删除托管的 object。

So, in your example, the newly created shared_ptr takes over ownership from the unique_ptr , leaving the latter owning nothing.因此,在您的示例中,新创建的shared_ptrunique_ptr接管所有权,而后者一无所有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM