1

I have a C++ function that takes as arguments something like:

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?

What are the conversions going on to allow this to compile?

Sigmund Fraud
  • 173
  • 1
  • 7
  • 2
    [There's a constructor](http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr) – chris Jul 13 '14 at 15:09

2 Answers2

1

It uses the following constructor of 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*". Since, in your example, T* is implicitly convertible to const T*, everything is fine. This is nice, of course, because it means that shared_ptrs behave just like raw pointers.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

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). 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.

Community
  • 1
  • 1
drewbarbs
  • 345
  • 3
  • 9