简体   繁体   中英

Default value as Global const vs. Function return value

In the book Programming Principles and Practice Using C++ by Bjarne Stroustrup in section 8.6.2 Global initialization, it is recommended to define default values (eg for date in a calendar) as follows:

const Date& default_date()
{
  static const Date dd(1970,1,1);
  return dd;
}

How does this method compare to simply having a global constant as follows?

static const Date dd(1970,1,1);

The default_date function is declared with external linkage which means it can be used from any translation unit which have a suitable declaration.

The global variable have internal linkage, and thus can only be used in the translation unit it's defined in.

Take a look here:

https://godbolt.org/z/Y6Dhbz

From purely a performance POV, the clear winners are:

Declaring as static const in a header file

static const Date dd(1970,1,1);

Using a constexpr

constexpr Date dd(1970,1,1);

Returning the default from an inline method.

inline Date default_date()
{
  return Date(1970,1,1);
}

How does this method compare to simply having a global constant as follows?

IF the method is compiled within the same compilation unit, then basically there is no difference. If however the default_date is extern, then you will incur a few extra loads. Personally, I'd just recommend using constexpr.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM