在C 11中,我想摆脱Pimpl Idiom中的原始指针

in C++11 I would like to get rid of the raw pointers in pimpl idiom

本文关键字:Idiom Pimpl 原始 指针      更新时间:2023-10-16

我想将原始指针(parent_)删除到PIMPL成语中的主类。什么是AG的最佳方法。这是一个示例:

//==============in "widget.h"
class Widget { 
public:
Widget() {};
…
private:
struct Impl;
std::unique_ptr<Impl> pImpl; 
};
//==== in .cpp 
#include "widget.h"
#include "gadget.h"
#include <string>
#include <vector>
struct Widget::Impl { 
Widget* parent_;
std::string name;
std::vector<double> data;
Gadget g1, g2, g3;
Impl (Widget* parent) : parent_ (parent) {}
};
Widget::Widget() 
: pImpl(std::make_unique<Impl>( this )) 
{} 

不要!

原始指针很好。RAW 拥有必须用智能的指针代替,但parent_没有任何东西。离开它是:)

C 11标准库的设计师非常 谨慎允许不完整的类型用于std::unique_ptrstd::shared_ptr,在某些情况下。

这样的实例主要集中在您能够使用Pimpl Idiom使用这些智能指针的焦点。这意味着您不需要裸露的指针。

有关更多详细信息,请参见http://en.cppreference.com/w/cpp/language/pimpl