Smart pointers are for managing ownership and lifetime, they allow us (amongst other things) to safely transfer ownership around the various parts of our code.
When you pass a const unique_ptr<T>&
to a function (irrelevant of whether T
is const
or not), what it actually means is that the function promises to never modify the unique_ptr
itself (but it could still modify the pointed-to object if T
is not const
) ie. there will be no possible transfer of ownership whatsoever. You're just using the unique_ptr
as a useless wrapper around a naked pointer.
So, as @MarshallClow suggested in a comment, you should just get rid of the wrapper and pass either a naked pointer or a direct reference. What's cool with this is that your code is now semantically clear (your function's signature clearly states that it does not mess with ownership, which was not immediately obvious with a const unique_ptr<...>&
) and it solves your "constification" problem at the same time!
Namely:
void someFunction(const AClass* p) { ... }
std::unique_ptr<AClass> ptr(new AClass());
someFunction(ptr.get());
Edit: to address your secondary question "why won't the compiler let me ... cast unique_ptr<A>
to unique_ptr<A const>
?".
Actually, you can move a unique_ptr<A>
to a unique_ptr<A const>
:
std::unique_ptr<A> p(new A());
std::unique_ptr<const A> q(std::move(p));
But as you can see this means a transfer of ownership from p
to q
.
The problem with your code is that you're passing a (reference to) unique_ptr<const A>
to a function. Since there is a type discrepancy with unique_ptr<A>
, to make it work the compiler needs to instantiate a temporary. But unless you transfer ownership manually by using std::move
, the compiler will try to copy your unique_ptr
and it can't do that since unique_ptr
explicitly forbids it.
Notice how the problem goes away if you move the unique_ptr
:
void test(const std::unique_ptr<const int>& p) { ... }
std::unique_ptr<int> p(new int(3));
test(std::move(p));
The compiler is now able to construct a temporary unique_ptr<const A>
and move the original unique_ptr<A>
without breaking your expectations (since it is now clear that you want to move, not copy).
So, the root of the problem is that unique_ptr
only has move semantics not copy semantics, but you'd need the copy semantics to create a temporary and yet keep ownership afterwards. Egg and chicken, unique_ptr
just isn't designed that way.
If you now consider shared_ptr
which has copy semantics, the problem also disappears.
void test(const std::shared_ptr<const int>& p) { ... }
std::shared_ptr<int> p(new int(3));
test(p);
//^^^^^ Works!
The reason is that the compiler is now able to create a temporary std::shared_ptr<const int>
copy (automatically casting from std::shared_ptr<int>
) and bind that temporary to a const
reference.
I guess this more or less covers it, even though my explanation lacks standardese lingo and is perhaps not as clear as it should be. :)