0

I have a c++ class which as a private data member has a struct defined:

Class example {

...

private:
   struct Impl;
   Impl& structure_;
};

Assuming that the struct Impl is defined as follows:

struct example::Impl{
    int m1;
    int m2;
    int m3;
};

how would I be able to initialize the struct instance ( structure_ ) in the class's constructor?

Right now I have:

example::example() :
     structure_ .m1(00),
     structure_ .m2(00),
     structure_ .m3(00) {
...
}

.. for the initialization list, but I'm getting this error:

'example::structure_' : must be initialized in constructor base/member initializer list

how would I fix this?

Thanks

4 Answers 4

1

Impl is a reference, so you need to initialize it with an actual Impl object before it can be used.

Sign up to request clarification or add additional context in comments.

Comments

1

If you're going for the pImpl idiom, use a pointer, and allocate + deallocate it in the class, then assign to it inside the ctor.

Class example {

...

private:
   struct Impl;
   Impl* pimpl_
};

example::example() :
     pimpl_(new Impl())
{
  pimpl_->m1 = 00;
  pimpl_->m2 = 00;
  pimpl_->m3 = 00;
...
}

example::~example(){
  delete pimpl_;
}

If you really want a reference, dereference the returned pointer from new and take its address again when deleting it:

example::example() : impl_(*new Impl(), ...

example::~example(){ delete &impl_; }

4 Comments

That's still isn't a valid ctor-initializer.
On a sidenote here: I generally try to suggest implementing the pimpl-idiom with a buffer of the correct size inside of the structure that hides the implementation. That way you won't have to do an extra l2-cache-miss/memory fetch everytime you try to call something on the instance. +1 for a good general pimpl-idiom description!
@Simon: This gets problematic as you can't be sure of the alignment sometimes. Or how do you know the size?
Yes that is indeed the problem. enum { IMPL_SIZE = 123; }; union { char implbuf[IMPL_SIZE]; double aligndummy; } impl; .. which aligns it with a pretty strict alignment according to the double-type, which can be changed according to your needs. Make sure to have an assert or static assert in the construction to make sure that your sizeof(impl) is equal to or smaller than the IMPL_SIZE to avoid mistakes.
1

Since your structure_ is a reference, it needs to be referenced by something that is created outside of your "example" class. You could either change the reference into a pointer and allocate the structure somehow, or define the structure in the class-definition, allowing you to instance it directly instead of using a reference.

Comments

0

You store your struct by reference in your class. A reference must point to a physical object, you can do two things. Store the object by value or by pointer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.