使用unique_ptr实现pimpl能自动管理内存、避免资源泄漏,并需在.cpp中定义析构函数以确保看到完整类型。1.传统pimpl用原始指针手动管理内存易出错;2.用unique_ptr后,需在头文件前置声明impl并在.cpp中定义其结构,确保析构时可见完整类型;3.拷贝操作需手动实现深拷贝,移动操作可默认或显式定义;4.必要时可用unique_ptr<t[]>或shared_ptr替代,但推荐优先使用unique_ptr<t>。

在C++中,Pimpl(Pointer to Implementation)是一种常见的设计惯用法,用来隐藏类的实现细节、减少编译依赖。而使用
unique_ptr

unique_ptr
传统的Pimpl写法是用原始指针指向一个不完整类型(也就是前置声明的类),然后手动在构造函数中new,在析构函数中delete。这种方式容易出错,比如忘记释放内存或者拷贝时出问题。
用
unique_ptr

unique_ptr
这是实现Pimpl的关键一步。因为Pimpl通常会用到未定义类型的
unique_ptr
unique_ptr
unique_ptr
解决方法是:将类的实现细节封装进.cpp

举个例子:
// widget.h
#pragma once
#include <memory>
class Widget {
public:
Widget();
~Widget();
private:
struct Impl; // 前置声明
std::unique_ptr<Impl> pImpl;
};// widget.cpp
#include "widget.h"
#include <string>
struct Widget::Impl {
std::string name;
int value;
};
Widget::Widget() : pImpl(std::make_unique<Impl>()) {}
Widget::~Widget() = default;这样就能安全使用
unique_ptr
.cpp
Impl
使用Pimpl之后,编译器默认生成的拷贝或移动操作不会自动生效,因为
unique_ptr
常见做法是:
pImpl
例如:
Widget(const Widget&); Widget& operator=(const Widget&); Widget(Widget&&) = default; Widget& operator=(Widget&&) = default;
在
.cpp
Widget::Widget(const Widget& other)
: pImpl(std::make_unique<Impl>(*other.pImpl)) {}注意这里用了
*other.pImpl
Impl
std::unique_ptr<T[]>
std::shared_ptr
虽然大多数情况下用的是
std::unique_ptr<T>
std::unique_ptr<T[]>
std::shared_ptr
不过还是建议优先用
unique_ptr<T>
基本上就这些。用
unique_ptr
以上就是怎样用智能指针实现Pimpl惯用法 unique_ptr在前置声明中的应用技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号