1

I'm not sure I understand how is this possible:

#include <memory>
#include <iostream>
using namespace std;

void f(const unique_ptr<int> &p){
    *p = 10; // no error here
}
int main(){
    unique_ptr<int> p (new int);
    *p = 0;
    cout << *p << endl;  // 0
    f(p);
    cout << *p << endl;  // 10 ??
    return 0;
}

I expected a compiler error since function parameter is const, but again, it's been bypassed and the value has been changed. Why?

Of course, if I use this:

 void f(const int* p){
    *p = 10;
}

and

f(p.get());

then I get expected compiler error.

Tracer
  • 2,544
  • 2
  • 23
  • 58
  • 3
    Same as `int* const` vs. `int const*`. – dyp May 07 '14 at 21:23
  • 3
    Do not pass a pointer as a `unique_ptr` if the function does not need to acquire the ownership. Just use a raw pointer or a reference to the object the smart pointer points to. – dyp May 07 '14 at 21:25

1 Answers1

4

You're making the reference to the pointer const, not what it points to.

djechlin
  • 59,258
  • 35
  • 162
  • 290