A
A
Alexander2020-04-16 18:18:56
C++ / C#
Alexander, 2020-04-16 18:18:56

What's the difference between passing by pointer and by reference?

There is a base class A.
There is a function bool foo(A &qw, A *qw2)
What difference does it make what to pass to the function, a reference to a class object, or a pointer to a class object.
In the first case, the inversion is qw.xx, and in the second case qw2->xx.
Please explain what is the difference. And how to be more correct.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2020-04-16
@Mercury13

About passing an object to a function - usually a reference , BUT!
1. If the library lives on pointers (Qt) - a pointer.

void fillCombo(QComboBox* x) {}  // хорошо
fillCombo(ui->comboHistory);

void fillCombo(QComboBox& x) {}  // плохо
fillCombo(*ui->comboHistory);

2. If NULL is possible, a pointer. BUT: there is a "Null object" pattern, and it is sometimes good.
// Хуже, но возможно
void import(AsyncRunner* asy) {
   if (asy) {
      asy->run([](){
        doImport(x);
      });
   } else {
      doImport(x);
   }
}
import(nullptr);

// Лучше
void import(AsyncRunner& asy) {
  asy.run([](){
    doImport(x);
  });
}
import(NoAsync::INST);

3. If we pass a data buffer - a pointer. 4. If the object is small, the value. The object may be large, but there are special registers for it - then ... There is one machine with such registers, I just don’t remember which one. Xbox? 5. Idiom "by value + move", which allows you to get rid of two versions of the function - Obj(string&) and Obj(string &&). Used for objects with simple movement and complex copying, usually STL strings and structures.
void write(size_t size, const char* data) {}
void save(std::string_view fileName) {}
void transform(Matrix4 x) {}
Obj::Obj(std::string aName) : name(std::move(aName)) {}

D
Denis Zagaevsky, 2020-04-16
@zagayevskiy

The pointer can be nullptr (do not point to anything). The reference cannot be uninitialized.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question