I make pretty extensive use of PImpl and something that I've found myself waffling on is where exactly to to initialize members of the Pimpl struct. Options are to create a constructor for the Private
struct and initialize them there, or to initialize them in the main class's constructor.
myclass.hpp:
class MyClass {
public:
MyClass();
~MyClass();
private:
struct Private; unique_ptr<Private> p;
};
myclass.cpp:
#include "myclass.hpp"
#include <string>
struct MyClass::Private {
int some_var;
std::string a_string;
// Option A
Private() :
some_var {42},
a_string {"foo"}
{}
};
MyClass::MyClass() : p(new MyClass::Private) {
// Option B
p->some_var = 42;
p->a_string = "foo";
}
At present I don't really see a difference between the two other than if I were, for some reason, to want to create new Private
objects or copy them around or something, then Option A might be preferable. It also is able to initialize the variables in an initialization list, for what that's worth. But, I find that Option B tends to be more readable and perhaps more maintainable as well. Is there something here I'm not seeing which might tilt the scales one way or the other?