gpt4 book ai didi

C++ 入门 5 版 : shared_ptr initialized from uniqe_ptr?

转载 作者:行者123 更新时间:2023-12-03 02:40:28 28 4
gpt4 key购买 nike

关于 C++ 入门 5 版。第12章动态内存:写道:

shared_ptr p(u); P assumes ownership from the uniqe_ptr u; makes u null. shared_ptr p(q, d) Assumes ownership for the object to which the built-in pointer q points. q must be convertible to T* ($4.11.2, p.161). p will use the callable object d ($10.3.2, p.388) in place of delete to free q.

  • 我不明白“假定来自 unque_ptr 以及内置对象的所有权...”。

谁能给我解释一下这一段吗?非常感谢。

最佳答案

这本书类型不清楚。您需要一个对 construct 的右值引用来自 unique_ptrshared_ptr:

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

检查此代码:

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

直播Godbolt

<小时/>

智能指针管理它们拥有的原始指针的生命周期。 unique_ptr 不共享所有权,而 shared_ptr 则共享所有权。当您从 unique_ptr 构造 shared_ptr 时,您必须通过移动放弃其所有权,并且 unique_ptr 无法复制。

我认为通过使用“假设所有权”,作者想要声明的是,如果您以某种方式修改智能指针拥有的指针,仍然可能会发生不好的事情。

关于C++ 入门 5 版 : shared_ptr initialized from uniqe_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58574708/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com