R
R
ReD2016-05-07 15:37:50
Programming
ReD, 2016-05-07 15:37:50

Can a constant pointer be considered analogous to a reference in C++?

Hello!
For example, a constant pointer:
*const Cat
and a reference:
&Cat
Can these ways of accessing an object be considered similar and interchangeable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2016-05-07
@trinitr0

No, but the difference is more significant than the ability to assign nullptr. A constant reference can extend the lifetime of a temporary object, but a pointer cannot.
For example, you can:

T f();
...
const T& obj = f();
obj.foo();

-- the object returned from function f will not be destroyed until obj goes out of scope.
And so - it is impossible:
T f();
...
const T* const obj = &(f());
obj->foo();

-- this code won't even compile because it takes the address of a temporary object.

Армянское Радио, 2016-05-07
@gbg Куратор тега Программирование

Нет. В указатель можно засунуть nullptr, а в ссылку - нет.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question