智能指针声明为 const
声明为 const 的智能指针只能调用用 const 标记的成员函数。所以它们的用途非常有限。
1.对于唯一指针,您不能更改将托管对象的所有权转移给另一个unique_ptr
甚至不从特定函数返回它。
所以我的问题是何时应该使用 const unique_ptr
2.对于共享指针,我认为使用 const shared_ptr
Smart pointers declared const
could only invoke the member functions marked with const
. So their usage is very limited.
1.For unique pointers, you could not change the transfer the ownership of the managed object to another unique_ptr
and not even return it from a specific function.
So my question is that when const unique_ptr<T>
should be used? Some simple example may help me to understand it better.
2.For shared pointers, I think it's meaningless to use const shared_ptr<T>
because you can never increase the counter of a specific const shared pointer.
If I wrong, please let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
回复:不可转移的唯一指针
是的,这就是重点。如果您有 const 对象,则无法修改它。因此,不允许从 const
unique_ptr
转移指针的所有权。示例:
现在
ResourceUser
的实例完全拥有一个以某种方式链接回该对象地址的资源。您永远不希望该对象在内存中移动。不需要任何额外的语法,例如ResourceUser a, b; a = move(b);
是不允许的。耶!从函数返回唯一指针的唯一有用原因是当您创建了一些传递回调用者的值或者您正在产生某些东西的所有权时 - 实际上这些是同一件事。使其成为常量是没有意义的。所以是的,无关紧要。请勿使用锤子拧入螺钉。
Re: Non-transferrable unique pointers
Yes, that's the point. If you have a const object you cannot modify it. Transferring ownership of a pointer either from or to a const
unique_ptr
is therefore not allowed.Example:
Now an instance of
ResourceUser
outright owns a resource that is in some way linked back to this object's address. You don't ever want that object to move in memory. Without needing any additional syntax, something likeResourceUser a, b; a = move(b);
is disallowed. Yaay!The only useful reason to return a unique pointer from a function is when you have created some value that is passed back to the caller or you are yielding ownership of something -- actually these are the same thing. It makes no sense to make it const. So yeah, irrelevant. Don't use a hammer to drive in a screw.
一种潜在的用例是,当您调用一个向您返回
shared_ptr
或unique_ptr
的函数时,并且您希望编译器保证对该对象的访问无法转义你的函数,例如:...至于为什么你想要这样做... Foo() 可能会做一些事情,使将来能够访问
*blah< /code> 不安全,所以最好的避免方法令人不快的运行时错误是让编译器确保这些访问不会发生,即使有人修改您的函数以尝试允许它。能够防御未来维护程序员的代码不太可能出现错误:)
One potential use-case would be when you've called a function that returns a
shared_ptr
orunique_ptr
to you, and you want the compiler to guarantee that the access to that object can't escape your function, e.g.:... as for why you'd want to do that... Foo() might do something that will make future access to
*blah
unsafe, and so the best way to avoid unpleasant runtime bugs is to have the compiler ensure that those accesses cannot happen, even if someone modifies your function to try to allow it. Code that can defends itself against future maintenance programmers is less likely to gather bugs :)