2

I want to create a class with a Pimpl (Private implementation). Normally you would do:

class A
{
private:
  class B;
  B* _pimpl = nullptr;
}

and then I would define it in the .cpp file. But I have to use dynamic allocation. Would it be possible to use an rvalue reference instead?

class A
{
public:
  A(); //Constructor to init rvalue reference
private:
  class B;
  B&& _pimpl;
}

And then in the .cpp file:


class A::B
{
public:
   int C = 3u;
}

//and then the constructor of A:

A::A() : _pimpl(B()) { } //now we should have a fresh b pimpl?

I'm currently on holidays and I only have my C++ book for reference. I read about rvalue references and thought it might work. What do you guys think?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Noel
  • 23
  • 2
  • Why not a simple reference? Why do you think you need to move `B`? – πάντα ῥεῖ Apr 27 '19 at 11:44
  • because i tought in order to do A::A() : _pimpl(B()) { } - to construct B into _pimpl i have to use rvalue because B() is an rvalue? But im not sure if this is right - but would it work with a normal reference ? – Noel Apr 27 '19 at 11:46
  • [It seems you're right](http://coliru.stacked-crooked.com/a/3715e6792f498012). If a simple reference is used the [compiler complains](http://coliru.stacked-crooked.com/a/07083e9a2d30066d). – πάντα ῥεῖ Apr 27 '19 at 11:51
  • 1
    Nitpick: "Pimpl (Private implemenation)" - Pimpl usually means "*Pointer* to implementation" :) – Jesper Juhl Apr 27 '19 at 12:14

1 Answers1

5

If by "work" you mean "compile", then sure.

But _pimpl(B()) is going to initialize _pimpl as a reference to a temporary. Member references don't extend lifetime, so this construct dangles almost immediately. Therefore no, it won't work.

A unique_ptr<B> is the better type to hold a pimpl (as a default choice). The need for dynamic allocation cannot generally be avoided. But the drawbacks may be mitigated if one chooses a good custom allocator.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458