简体   繁体   中英

Alternative way to initialization members in C++03

today I have a few questions to you but the first let me start with brief introduction.

In my work I meet structs which contain many members. Those structs are assignable and copyable. It is not comfortable initialize its by initializer list of ctros. Lately I got the idea that initialize those members by assigning global object of that class instead doing it by initializer list. I know that global objects are initialized by zeros automaticaly.
I assume that global objects of non POD structures are clearing together with its members - correct me if I am wrong, please.

I have written sample code which present that situation

#include <iostream>

struct Foo
{
  double x;
  void example() { }
};

struct Bar;
Bar const& Init();

struct Bar
{
  int i;
  double d;
  Foo f;

  Bar()
  {
    if( this != &Init() ) // is it necessary? 
      *this = Init();
  }
};

const Bar GLOBAL_BAR;
Bar const& Init()
{
  return GLOBAL_BAR;
}

void print_bar( const Bar& bar )
{
  std::cout << bar.i << ' ' << bar.d  << ' ' << bar.f.x << "\r\n";
}

int main() 
{
  std::cout << "Global object: ";
  print_bar( GLOBAL_BAR );

  std::cout << "Local object: ";
  Bar bar;
  print_bar( bar );

  std::cout << "Temp objecy: ";
  print_bar( Bar() );

  return 0;
}

My questions are:

  1. Is it correct code in c++03 standard sense?
  2. Does condition inside ctor is necessary?
  3. If I remove condition from ctor code works properly. Why are there no any cyclic call the ctor while GLOBAL_BAR construction ?
  4. Do you know another alternative construction which may substitute standard way to initialize members by initialization list?
  1. Yes (don't see why not)
  2. Not needed in this case
  3. In this case the struct is constructed once and all the struct fiels are just copied into themselves - so nothing happens
  4. At least memset() comes to my mind. I would still bite the bullet and just use the initializer list. These kind of things are hacks and bad programming practice that might hit you later when you debug some mysterious bugs

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