Arminw
Arminw

Reputation: 39

C++ call by reference or not /?

Which one of those two methods should i use?

int Foo= XXX::instance().yyy(NULL);

OR

auto &q = XXX::instance();
int Foo = q.yyy(NULL);

Upvotes: 1

Views: 63

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Using the form

auto &q = XXX::instance();
int Foo = q.yyy(NULL);

has at least two clear advantages:

  1. It's shorter to write q.foo(), instead of having to write XXX::instance().foo() everywhere you need the instance

  2. Supposed that XXX is a Singleton, and that's generally considered a bad design (because you have a direct coupling to XXX), that form would make it way easier to refactor the code later, as soon you want to replace XXX with a more generic interface.

Upvotes: 3

likle
likle

Reputation: 1797

I would use

auto &q = XXX::instance();
int Foo = q.yyy(NULL);

for the following reasons:

  • You can inspect the variable when you are debugging more easily
  • Entering the function with your debugger becomes more clear in some IDEs
  • Scrolling vertically is easier on most devices
  • The compiler will optimize it for you
  • If you add further calls you can just use q. instead of repeating yourself.

Upvotes: 0

Related Questions