Replacing the stack against a static variable with a struct instance containing const member

Using gcc version 4.4.3 as follows:

gcc -g -x c++ -lstdc++ -std=c++98 -o ./main ./main.cpp 

this code in main.cpp compiles fine:

 #include <iostream> struct A { A() : m_flag(false) { } const bool m_flag; }; static A aa = A(); int main(int argc, char* argv[]) { A a; // Not static = copy OK A b( a ); A c = b; A d = A(); // Static = copy not OK // aa = A(); } 

But if I uncomment aa = A(); , I get:

 ./main.cpp: In member function 'A& A::operator=(const A&)': ./main.cpp:4: error: non-static const member 'const bool A::m_flag', can't use default assignment operator ./main.cpp: In function 'int main(int, char**)': ./main.cpp:24: note: synthesized method 'A& A::operator=(const A&)' first required here 

Why do default copy building and copy assignment work for copies on the stack, but not when replacing non-constant static with a copy?

+4
source share
1 answer

The problem is this line:

  const bool m_flag; ... aa = A(); // invokes 'A::operator =(const A&)` 

which calls operator = by default. Changing the const member is a trivial mistake.

 A b( a ); // all invoke `A::A(const A&)` A c = b; A d = A(); 

calls the default copy constructor (not operator = , as you assume), where m_flag assigned a new value during initialization itself.

+4
source

Source: https://habr.com/ru/post/1381057/


All Articles