是否可以使用右值引用作为pimpl句柄?

问题描述 投票:2回答:1

我想用Pimpl(私有实现)创建一个类。通常你会这样做:

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

然后我会在.cpp文件中定义它。但我必须使用动态分配。是否可以使用右值参考?

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

然后在.cpp文件中:


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?

我目前正在度假,我只有我的C ++书籍供参考。我读到了rvalue引用,并认为它可能有用。你们有什么感想?

c++ c++11 reference rvalue-reference pimpl-idiom
1个回答
5
投票

如果通过“工作”你的意思是“编译”,那么肯定。

_pimpl(B())将初始化_pimpl作为临时参考。成员引用不会延长生命周期,因此此构造几乎立即悬挂。因此不,它不会起作用。

unique_ptr<B>是持有pimpl的更好类型(作为默认选择)。通常不能避免对动态分配的需要。但是如果选择一个好的自定义分配器,可以减轻这些缺点。

© www.soinside.com 2019 - 2024. All rights reserved.