Home > Net >  How can I initialize this pointer correctly to avoid a segmentation fault?
How can I initialize this pointer correctly to avoid a segmentation fault?

Time:11-16

This is my class structure

class A
{
   public:
     void doSomething {
        bInstance -> bMethod();
     }
   ...
   private:
      std::shared_ptr<B> bInstance
}

class B
{
    public:
       void bMethod();
}

A::A(std::shared_ptr<B> bInstance)
    : bInstance(bInstance){}

Then using GTest, this is my test fixture

// Test Fixture
class ATest: public ::testing::Test {
protected:
    ATest()
    : bInstancePointer(std::make_shared(...)), 
      aInstance(bInstancePointer)
    {}

    A aInstance;
    std::shared_pt bInstancePointer;
};

In my test I have

aInstance.doSomething()

This results in a segmentation fault. Does anyone know why this syntax is incorrect or have any suggestions on how I can restructure the initialization of my pointers to avoid this segmentaion error?

CodePudding user response:

Just fix the order of members' declaration:

// Test Fixture
class ATest: public ::testing::Test {
protected:
    ATest()
    : bInstancePointer(std::make_shared(...)), 
      aInstance(bInstancePointer)
    {}

    std::shared_pt bInstancePointer;
    A aInstance;
};
  •  Tags:  
  • c
  • Related