how to use Pimpl pattern with dependencies between members

  c++

following code is abstraction of my condition

// header file
#pragma once
#include <memory>

class B;
class C;
class A {
public:
    A();
    B& GetB();
    C& GetC();

private:
    class Impl;
    std::unique_ptr<Impl> impl_;
};

// source file
#include "Header.h"
#include <iostream>

class B {
public:
    B(A* a) : a_(a) {

    }
    
    void Welcome() {
        std::cout << "welcome B" << std::endl;
    }
private:
    A* a_;
};

class C {
public:
    C(A* a) : b_(a->GetB()) { // 1. request reference of B
        b_.Welcome(); // 3. it occurs undefined behavior because b is member of uninitialized impl_
    }
private:
    B& b_;
};

class A::Impl {
public:
    Impl(A* a) : b_(a), c_(a) {}
    B& GetB() {
        return b_;
    }
    C& GetC() {
        return c_;
    }
private:
    B b_;
    C c_;
};

A::A() {
    impl_ = std::make_unique<Impl>(this);
}

B& A::GetB() {
    return impl_->GetB(); // 2. impl_ is not initialized
}

C& A::GetC() {
    return impl_->GetC();
}

int main() {
    A a;
}

I’m trying to use pimpl pattern but I don’t know how to manage dependencies between members. I cannot pass reference of class Impl because It is uncompleted type…. should I have to use kind of lazy initialization strategy? all member has setter function? I think it need builder or factory for safety if I decide to use that strategy right?

Source: Windows Questions C++

LEAVE A COMMENT