0

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?

committedandroider
  • 8,711
  • 14
  • 71
  • 126
  • 1
    albeit it might not be the reason, but the order of member declaration is not the same as the order of initialization in constructor. Fix it, then see if it helps – Sergey Kolesnik Nov 16 '21 at 09:26
  • https://stackoverflow.com/questions/1242830/constructor-initialization-list-evaluation-order – Kenneth Davis Nov 16 '21 at 09:27
  • Have you checked if `bInstance` is null when you call it? – VLL Nov 16 '21 at 09:28
  • Also, it doesn't seem that you need `std::shared_ptr` (since you are the one to create it in the first place). Just store `Instance` as an object and pass it as a reference to `class A`. – Sergey Kolesnik Nov 16 '21 at 09:30
  • 1
    Please provide a [mre]. – kiner_shah Nov 16 '21 at 09:32
  • 1
    @SergeyKolesnik After fixing the ordering, I don't see the segmentation fault anymore. – committedandroider Nov 16 '21 at 09:35
  • @kiner_shah yup thanks. I try to do that for this and for the future – committedandroider Nov 16 '21 at 09:35
  • Many compilers will warn you that the initializer list order doesn't math the declaration order. Members are initialized in declaration order, not initializer list order, which seems to have confused you. The syntax is technically correct - the compiler understands exactly what you wrote. But what you wrote is not not what you intended. – MSalters Nov 16 '21 at 09:44

1 Answers1

2

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;
};
Sergey Kolesnik
  • 3,009
  • 1
  • 8
  • 28