mardi 29 septembre 2015

make_shared makes a segfault

So - I have a shared_ptr which shall get a new content. But while trying that, I get a segfault.

The class will be used by the shared_ptr later:

class MatrixClass
{
public:
  MatrixClass(const MatrixClass &other)
    : matrix(
      std::make_shared<std::vector<std::vector<MyListType> > >(
        (*other.matrix).begin(),
        (*other.matrix).end()
      )
    )
  {
  }

  MatrixClass(std::initializer_list<std::initializer_list<MyListType> > &matrixIn)
    : matrix(
      std::make_shared<std::vector<std::vector<MyListType> > >(
        matrixIn.begin(),
        matrixIn.end()
      )
    )
  {
  }

  virtual ~MatrixClass() = default;

private:
  std::shared_ptr<std::vector<std::vector<MyListType> > > matrix;
};

The class that generates the segfault:

class SomeClass
{
public:
  SomeClass()
  {
    // fill contents field of this class
    // (left out here for simplicity of the example code)

    this->Regenerate();
  }

  // calling this once is okay,
  // but twice results in Segmentation violation signal
  Regenerate()
  {
    int possibleContents = this->contents.size();
    int contentNumber = myrand(0, possibleContents - 1);
    auto matrix = this->contents[contentNumber];

    this->myMatrix = std::make_shared<MatrixClass>(
      matrix
    );
  }

  std::shared_ptr<MatrixClass> GetMatrix() const
  {
    return this->myMatrix;
  }

private:
  std::shared_ptr<MatrixClass> myMatrix;

  // contents is filled in the constructor
  std::vector<std::initializer_list<std::initializer_list<MyListType> > > contents;
};

And some code to run it:

int main()
{
  auto someClass = std::make_shared<SomeClass>();

  auto firstMatrix = someClass->GetMatrix();

  someClass->Regenerate(); // throws segfault

  auto secondMatrix = someClass->GetMatrix();

  // here would be some code to check that
  // firstMatrix does not equal secondMatrix 

  return 0;
}

So what is going wrong here?

Aucun commentaire:

Enregistrer un commentaire