jeudi 4 mai 2017

C++ 11/14 Unique Pointer not so unique?

I have just stabled upon a situation were a unique_pointer reference was passed as function argument. So I took a look at it and found out that the code was actually comping and running.

Why is that possible? How is a pointer unique when you can have reference of that pointer?

Here my example:

class Foo{
    public:
    int bar{23};
};

void Bar(std::unique_ptr<Foo>& a_foo){
    a_foo->bar = 42;
}

int main(int argc, char *argv[]){

    auto foo{ std::make_unique<Foo>() };
    Bar(foo);
    std::cout << foo->bar << std::endl; //outputs 42

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire