C++ 入门 5 版:shared_ptr 从 uniqe_ptr 初始化?
C++ primer 5 edition: shared_ptr initialized from uniqe_ptr?
关于 C++ primer 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*
(.11.2, p.161).
p
will use the callable object d
(.3.2, p.388) in place of delete
to free q
.
- 没看懂"Assumes ownership from the
unque_ptr
and for the object to which the built-in..."。
谁能给我解释一下这一段?非常感谢。
智能指针'own'(或者更好,'manage')底层原始指针或对象。
unique_ptr
完全拥有指针,并在超出范围时将其删除。 shared_ptr
可能与其他 shared_ptr
共享所有权,当最后一个 shared_ptr
超出范围时,托管对象将被删除。
因此,在您的示例中,新创建的 shared_ptr
接管了 unique_ptr
的所有权,而后者一无所有。
这本书的类型不清楚。您需要 construct a shared_ptr
来自 unique_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
。
我认为通过使用 "assumes ownership" 作者想说明的是,如果您以某种方式修改智能指针拥有的指针,坏事仍然可能发生。
关于 C++ primer 5 版。第12章动态内存:写成:
shared_ptr p(u); P assumes ownership from the
uniqe_ptr
u
; makesu
null. shared_ptr p(q, d) Assumes ownership for the object to which the built-in pointerq
points.q
must be convertible toT*
(.11.2, p.161).p
will use the callable objectd
(.3.2, p.388) in place ofdelete
to freeq
.
- 没看懂"Assumes ownership from the
unque_ptr
and for the object to which the built-in..."。
谁能给我解释一下这一段?非常感谢。
智能指针'own'(或者更好,'manage')底层原始指针或对象。
unique_ptr
完全拥有指针,并在超出范围时将其删除。 shared_ptr
可能与其他 shared_ptr
共享所有权,当最后一个 shared_ptr
超出范围时,托管对象将被删除。
因此,在您的示例中,新创建的 shared_ptr
接管了 unique_ptr
的所有权,而后者一无所有。
这本书的类型不清楚。您需要 construct a shared_ptr
来自 unique_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
。
我认为通过使用 "assumes ownership" 作者想说明的是,如果您以某种方式修改智能指针拥有的指针,坏事仍然可能发生。