mardi 7 juin 2022

Defer calling constructor of member object declared in header until source file

I'd like to do declare a member object within the class declaration within my header file. I want to defer the calling of the member's constructor until the corresponding source file. This is ideally what I'd like, just for illustration:

// foo.h
class Bar;
class Foo : public Base {
  Foo(int a);
  Bar  b;  // I don't want to construct here!
  ...
// foo.cc
Foo::Foo(int a)
  : base(a)
  , b("first", "second")  // <-- construct here
{}

Changing the type of b to a pointer will ripple through too many things.

Changing it to a REFERENCE is probably tenable.

// foo.h
class Bar;
class Foo : public Base {
  Foo(int a);
  Bar&  b;  // now it's a non-constant reference, but unassigned, and ok because no constructor!
  ...
// foo.cc
Foo::Foo(int a)
  : base(a)
  , b{"first", "second"}  // <-- construct here
{}

However, this results in the error: non-const lvalue reference to type 'Bar' cannot bind to an initializer list temporary. That makes sense too.

I guess I'm asking how would you do this? Is something like std::reference_wrapper going to be useful?

C++11 is a restriction.

Aucun commentaire:

Enregistrer un commentaire