开发者

Initialization of a struct instance data member in constructor?

开发者 https://www.devze.com 2023-03-09 20:29 出处:网络
I have a c++ class which as a private data member has a struct defined: Class example { ... private: struct Impl;

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


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


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_; }


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消