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:
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.