[英]Converting (implicit) boost shared_ptr<T> to shared_ptr<const T>
I have a C++ function that takes as arguments something like: 我有一个C ++函数,其参数如下:
void myFunction(shared_ptr<const MyObject> ptr)) {
...
}
and in my main code I do something like this, and it compiles: 在我的主要代码中,我做了这样的事情,它编译为:
shared_ptr<MyObject> test(new MyObject());
myFunction(test);
Does this mean that inside MyFunction, if I dereference ptr, then the object is constant and cannot be modified? 这是否意味着在MyFunction中,如果我取消引用ptr,则该对象是恒定的并且无法修改?
What are the conversions going on to allow this to compile? 进行哪些转换才能编译?
It uses the following constructor of std::shared_ptr
: 它使用以下
std::shared_ptr
构造函数:
template<class Y> shared_ptr(const shared_ptr<Y>& r) noexcept;
Which is defined to "not participate in the overload resolution unless Y*
is implicitly convertible to T*
". 定义为“除非
Y*
可隐式转换为T*
否则不参与过载解析”。 Since, in your example, T*
is implicitly convertible to const T*
, everything is fine. 由于在您的示例中,
T*
可隐式转换为const T*
,所以一切都很好。 This is nice, of course, because it means that shared_ptr
s behave just like raw pointers. 当然,这很好,因为这意味着
shared_ptr
的行为就像原始指针一样。
The code compiles because there is a constructor of shared_ptr<const MyObject>
that takes a shared_ptr<MyObject>
(shown in Joseph Mansfield's answer), since a const MyObject
can be bound without issue to a MyObject
(see What is a converting constructor in C++ ? What is it for? and MSDN ). 代码会编译,因为有一个
shared_ptr<const MyObject>
的构造shared_ptr<const MyObject>
采用了shared_ptr<MyObject>
(如Joseph Mansfield的答案所示),因为const MyObject
可以毫无问题地绑定到MyObject
(请参阅C ++中的转换构造函数) ?它是做什么用的?和MSDN )。 Indeed, if you try to modify the value pointed to by ptr
in myFunction
, then you will get compilation errors indicating that you are trying to modify a constant object. 确实,如果您尝试修改
myFunction
ptr
指向的值,则将出现编译错误,表明您正在尝试修改常量对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.