代码之家  ›  专栏  ›  技术社区  ›  committedandroider

如何正确初始化此指针以避免分段错误?

c++
  •  1
  • committedandroider  · 技术社区  · 3 年前

    这是我的班级结构

    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){}
    

    然后使用GTest,这是我的测试夹具

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

    在我的测试中我有

    aInstance.doSomething()
    

    这会导致分段错误。是否有人知道此语法不正确的原因,或者对如何重新构造指针的初始化以避免此分段错误有任何建议?

    1 回复  |  直到 3 年前
        1
  •  2
  •   Sergey Kolesnik    3 年前

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