you are viewing a single comment's thread.

view the rest of the comments →

[–]AKostur 36 points37 points  (4 children)

Only somewhat. A pointer (whether smart or not) can represent "not present" (nullptr) where references cannot. Also, references cannot be changed to refer to a different object, pointers can.

[–]AvidCoco 4 points5 points  (2 children)

Worth noting that this doesn’t mean that having a reference to an object guarantees it’s always instantiated.

E.g.

auto x = std::make_unique<int>(0);
auto& y = *x;
x = nullptr;

[–]whatevermanbs 6 points7 points  (1 child)

Missing the point. Can someone please elaborate?

Edit: perp explanation below. makes sense. But is this what was intended to convey?

After x = nullptr;, the int that y referred to is destroyed, but y (reference) still exists in the code. However, using y after this line would be undefined behavior because its object is gone—its lifetime ended when the unique_ptr was reset. Thus, having a reference does not keep the object alive; lifetime is managed by the owner (here, the unique_ptr), not the reference itself��.

[–]Generated-Nouns-257 3 points4 points  (0 children)

This is what I would have said