Basti
Basti

Reputation: 2438

const reference to a pointer can change the object

const references make sure you can't change the object you're referring to. For example:

int i = 1;
const int& ref = i;
ref = 42; // error, because of a const reference

But if you use a reference to a pointer or a unique_ptr, you can. Example:

class TinyClass {
public:
    int var = 1;
    void f1() { var = 42; }
};

std::unique_ptr<TinyClass> pointer(new TinyClass);
const std::unique_ptr<TinyClass>& constRef = pointer;
constRef->f1(); // no error

I assume this happens because the pointer itself wasn't changed. But this feels misleading, or like an easy mistake. Is there a simple way to declare a "real" const reference to a pointer? As in: makes sure the object itself is const.

edit: Assume that I can't just change the type of the unique_ptr. A real-world scenario would be that some objects are constructed in a vector<unique_ptr<C>> and some function gets a (const) reference to one of its elements.

Upvotes: 4

Views: 1992

Answers (1)

Humam Helfawi
Humam Helfawi

Reputation: 20264

The const in const std::unique_ptr<TinyClass>& constRef guarantees that constRef will not point to another object once it set up. It has nothing to do with the object itself.

If you want to prevent changing the object itself:

std::unique_ptr<const TinyClass> ptr_to_const_object;

Edit (after OP's edit):

You can not do anything. Since there is a function which wants const vector<unique_ptr<C>>&, the function clearly tells you that it needs to play with the object inside the pointer (and even the pointer) but it does not need to change the vector items (like adding new item or deleting it).

Upvotes: 4

Related Questions