mercredi 22 janvier 2020

C++: Static vector defined in base class loses it's value in main

I defined a static vector (to be used as a default argument to one of the member function) in base class (Base1). When I inherit this class along with Base2 class in the Derived class, the value of the static vector is fine in the derived class constructor. However it is lost inside main() function.

base2.hh

class Base2 {
 public:
  static std::vector<uint32_t> AllPorts;
  void Reset(const std::vector<uint32_t>& port_nums = AllPorts);

  Base2() {
    for (int i = 0; i < 31; i++) {
      AllPorts.push_back(i);
  };
};

derived.hh

class Derived : Base1(), Base2() {
  Derived() {
     //value of AllPorts is intact here.
  };
}

derived.cc

//Instantiation of the Derived class
class Derived obj;

base1.cc

int main () {
  //value of AllPorts is lost.
}

Here are gdb debugs displaying the same.

 (gdb) b Derived::Derived()  
Breakpoint 1 at 0x3dac1: file derived.hh, line 27. 
 (gdb) b main 
Breakpoint 2 at 0x497f0: file base1.cc, line 539. 
 (gdb) start 
 Starting program:  [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". [New Thread 0x7ffff43b8700
 (LWP 15789)] [New Thread 0x7ffff3bb7700 (LWP 15790)]

 Thread 1 "daemon" hit Breakpoint 1, Derived::Derived()
 (this=0x555555a41800 <obj>) at derived.hh:27 27        Derived() :
 Base1(), Base2(){ 
 (gdb) n

 28          std::cout << "Inside Derived constructor. (this,
 AllPorts.size) = " << this << ", " << AllPorts.size() << std::endl;

 (gdb) p Base1::AllPorts  
 $1 = std::vector of
 length 32, capacity 32 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
 30, 31} 

 (gdb) c 
 Continuing. 

 Inside Derived constructor. (this,
 AllPorts.size) = 0x555555a41800, 32

 Thread 1 "daemon" hit Breakpoint 2, main (argc=3, argv=0x7fffffffea68)
 at base1.cc:539 
 539       xyz temp_obj;

 (gdb) p Base1::AllPorts 
 $2 = std::vector of length 0,
 capacity 0
 (gdb)

Any ideas on what could be going wrong? Thanks in advance.

Additional info: 'daemon' executable is created from derived.cc and this exe is linked to the 2 libraries - one created from base1.cc and other from base2.cc. Note that main is defined in base2.cc.

Also, noted that if the static variable is of built-in data-type, the value is not lost in main(). Tried with int and std::string, value is not lost when static variable is of type int, while it's lost with type std::string.

Aucun commentaire:

Enregistrer un commentaire