Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading