class widget
{public:
widget();
~widget();
private:
std::string name;
std::vectordata;
};
#pragma once
class widget
{public:
widget();
~widget();
private:
struct Impl;
struct Impl *pImpl;
};
#include "widget.h"
#include#include#include "Gadget.h"
struct widget::Impl {std::string name;
std::vectordata;
Gadget g;
};
widget::widget()
:pImpl(new Impl())
{}
widget::~widget()
{delete pImpl;
}
#pragma once
#includeclass widget
{public:
widget();
~widget();
widget(const widget& rhs);
widget &operator=(const widget& rhs);
widget(widget &&rhs);
widget &operator=(widget &&rhs);
private:
struct Impl;
std::unique_ptrpImpl;
};
#include "widget.h"
#include#include#include "Gadget.h"
struct widget::Impl {std::string name;
std::vectordata;
Gadget g;
};
widget::widget()
:pImpl(std::make_unique())
{}
widget::~widget() = default;
widget::widget(const widget & rhs)
:pImpl(std::make_unique(*rhs.pImpl))
{}
widget &widget::operator=(const widget& rhs)
{*pImpl = *rhs.pImpl;
return *this;
}
widget::widget(widget && rhs) = default;
widget &widget::operator=(widget &&rhs) = default;
在不进行资源共享的前提下,为达到实现PImpl惯用法的目的,应该选择使用std::unique_ptr智能指针,因为对象内部的pImpl指针拥有相应实现对象的专属所有权。(含义清晰,但是编码复杂)
#pragma once
#includeclass widget
{public:
widget();
widget(const widget& rhs);
widget &operator=(const widget& rhs);
private:
struct Impl;
std::shared_ptrpImpl;
};
#include "widget.h"
#include#include#include "Gadget.h"
struct widget::Impl {std::string name;
std::vectordata;
Gadget g;
};
widget::widget()
:pImpl(std::make_shared())
{}
widget::widget(const widget & rhs)
:pImpl(std::make_shared(*rhs.pImpl))
{}
widget &widget::operator=(const widget& rhs)
{*pImpl = *rhs.pImpl;
return *this;
}
为什么同样是智能指针却有如此大的差别?你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧