1

In one of my project I managed to fix a bug switching from a std::vector of objects to a std::vector of pointers to the object. Using the debugger I found that the error occurred when I was calling the std::vector<T,Allocator>::clear that it is supposed to destroy the objects stored in the vector. I am happy I solved the issue but I would like to know why I was able to! Here I attach the code incriminated:

#include <vector>
#include <memory>
#include <string>

class Base
{
 public:
 Base(int a);
 Base(const Base& o)=default;
 Base& operator=(const Base& o)=default;
 Base(Base&& o)=default;
 Base& operator=(Base&& o)=default;
 virtual ~Base()=default;
 virtual void Do();
};

class Derived: public Base
{
 private:
 std::string b;
 public:
 Derived(int a, std::string& b) : Base(a), b(b) {}
};

//Other derived classes from Base overriding Do



class Main{
 private:
std::vector<Derived> v;
public:
 Main();
 void Do(int i, std::string& b){
/*
   if something happens 
       v.emplace_back(a, b);// push_back equivalently for our purpose 
       
   if something else happens
       v.erase(iterator)    
*/
}
void reset(){
  v.clear();
}
};

class Main1{
private:
 std::vector<std::unique_ptr<Derived>> v;
public:
 Main1();
 void Do(int i, std::string& b){
/*
   if something happens 
       v.push_back(std::unique_ptr<Derived>(new Derived(i, b)));
       
   if something else happens
       v.erase(iterator)    
*/
}
void reset(){
  v.clear();
}
};


int main()
{

Main m;
for(int i=0; i<101; ++i){
//something
m.Do(i, b);
//something
if(i%10==0)
    m.reset(); //The bug is here. If I use Main1 everything runs smoothly
}

return 0;
}

This is a simplified version of the code that creates me problem. I hope that the detail are enough to give the correct contest for the answer. The debugger points me deep in the code defining what a deconstructor does reporting a segmentation fault, and personally I cannot understand what that code does. The compiler I am using is g++ 10.1 with the std=c++17 flag.

apelle
  • 144
  • 1
  • 9
  • The above code doesn't run. If you can supply a fully reproducible sample, you may get better answers from the community. I can't even take a good guess from just above. Maybe you blew up memory somewhere that is hidden when you push memory in a different order? Maybe something else? The error message and stack trace would also help others to discover the issue as well. – Michael Dorgan Dec 07 '20 at 18:31

0 Answers0