I was reading Effective C++ 3rd Edition. In page 70, the author says:
Like virtually all smart pointer classes,and
tr1::shared_ptralso overload the pointer dereferencing operators (
operator->), and this allows implicit conversion to the underlying raw pointers (...)
bool taxable1 = !(pi1->isTaxFree());
bool taxable2 = !((*pi2).isTaxFree());
unique_ptr<int> test(new int);
(*test) = 5;
Well, here's the thing. There is no implicit conversion to the underlying pointer, you have to call a specific
get member function (it's a theme in the standard library, think
But that's a good thing! Implicitly converting the pointer can break the guarantees of
unique_ptr. Consider the following:
std::unique_ptr<int> p1(new int); std::unique_ptr<int> p2(p1);
In the above code, the compiler can try to pass
p1s pointee to
p2! (It won't since this call will be ambiguous anyway, but assume it wasn't). They will both call
delete on it!
But we still want to use the smart pointer as if it was a raw one. Hence all the operators are overloaded.
Now let's consider your code:
(*test) = 5;
unique_ptr::operator* which produces an
int&1. Then you try use the subscript operator on it. That's your error.
If you have a
std::unique_ptr<int> than just use the
operator overload that the handle provides:
test = 5;
1 As David Scarlett pointed out, it shouldn't even compile. The array version isn't supposed to have this operator.