Noel
Noel

Reputation: 23

Is it possible to use an rvalue reference as pimpl handle?

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?

Upvotes: 2

Views: 143

Answers (1)

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.

Upvotes: 5

Related Questions