Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top