user2544133
user2544133

Reputation:

Return static const value

Is declaring static const array inside getter function is reasonable way of keeping code coherent? I never saw it before, but in code review I found something like this:

static const std::array<std::string, 4>& fooArrayGetter()
{
  static const std::array<std::string, 4> fooArray =
    {"foo" ,"bar", "baz", "qux"};
  return fooArray;
}

It looks correct: array is allocated only once, quite elegant because getter is combined with its value, but running it inside Godbolt https://godbolt.org/z/K8Wv94 gives really messy assembler comparing to making whole operation in more standard way. As a motivation for this code I received reference to Item 4 from Meyers' Efficient C++

Edit: GCC compiler with --std=c++11 flag

Upvotes: 1

Views: 205

Answers (2)

Marek R
Marek R

Reputation: 37647

Warning

static keyword here has two different meanings!

  • This which you thing applies to return value says: function fooArrayGetter should be visible only in this translation unit (only current source code can use this function)! This doesn't have any impact on return value type!

  • this inside a function says: variable fooArray has lifetime like a global scope (it is initialized on first use of fooArrayGetter and lives as long as application). This static makes returning a const reference a safe thing to do since makes this variable/constant ethernal.

Upvotes: 2

eerorika
eerorika

Reputation: 238311

Is declaring static const array inside getter function is reasonable way of keeping code coherent?

It can be. It can also be unnecessarily complicated if you don't need it. Whether there is a better alternative depends on what you intend to do with it.

gives really messy assembler

Messiness of non-optimised assembly rarely matters.

Upvotes: 3

Related Questions