L
L
lightalex2018-11-16 19:23:03
C++ / C#
lightalex, 2018-11-16 19:23:03

What is the difference between *& and * in C++?

Good day

void test(Book* obj) {
  obj->a = 2;
  std::cout << obj->a;
}
Book *book = new Book();
test(book);

void test(Book*& obj) {
  obj->a = 2;
  std::cout << obj->a;
}
Book *book = new Book();
test(book);

What is the difference between *& and * in these cases?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2018-11-16
@lightalex

The first is a pointer * to Book.
The second is a reference & to a pointer * to Book.
This means that by changing the contents of the pointer in the second case, you will actually change the contents of the pointer in the code that called this function - the book pointer.
But specifically in this example, the pointer does not change. And that means there is no difference.
There is another effect. When code outside of this function changes the book pointer (for example, another thread does), then this function can immediately see the changes. But there are subtleties with caching and volatile.
UPD: there is still a difference. In the variant with a link, there is an additional level of indirect addressing. Which means it's a bit slower.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question