https://rentry.org/PPP2_p293

// Code derived from Stroustrup's PPP2 book
// § 8.6.2 Global initialization
//  -and beginning on p 293

#include <iostream>

using namespace std;

//------------------------------------------------------------------------------
// as filename: f1.cpp

int x_1 = 1;
int y_1 = x_1 + 2;  // y_1 becomes 3

//------------------------------------------------------------------------------
// as filename: f2.cpp

extern int y_1;
int        y_2 = y_1 + 2;  // y_2 becomes 2 or 5 (bad)

//------------------------------------------------------------------------------

struct Date {
  Date(int y, int m, int d) : y{y}, m{m}, d{d} {}

  int y;
  int m;
  int d;
};

namespace good {
const Date default_date{1970, 1, 1};  // the default date is January 1 1970.
}  // namespace good

namespace better {
const Date default_date()  // return the default Date
{
  return Date{1970, 1, 1};
}
}  // namespace better

namespace best {
const Date& default_date()
{
  static const Date dd{1970, 1, 1};  // initialize dd first time we get here

  return dd;
}
}  // namespace best

int main()
{
  Date d1 = good::default_date;
  Date d2 = better::default_date();
  Date d3 = best::default_date();

  cout << d1.y << d2.y << d3.y << '\n';
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_08/main_p293.cpp && ./a.out

PrevUpNext

Edit
Pub: 04 Apr 2023 15:16 UTC
Edit: 03 May 2023 00:46 UTC
Views: 531