如何为含隐式删除拷贝构造函数的类编写工厂方法?
解决方案
因为std::mutex既不可拷贝也不可移动,你的类TheClass会被隐式删除拷贝和移动构造函数,导致值返回的工厂函数无法编译。以下几种方法可以实现你的需求:
1. 返回std::unique_ptr<TheClass>
通过动态分配实例并返回智能指针,彻底规避拷贝/移动操作:
#include <memory> std::unique_ptr<TheClass> CreateTheClassInstance() { return std::make_unique<TheClass>("specific args", specific_int); }
使用时修改成员变量类型并初始化:
SomethingElse() : _the_class(CreateTheClassInstance()) { } std::unique_ptr<TheClass> _the_class;
2. 工厂函数原地构造对象
如果不想用动态分配,可以让工厂函数在目标对象的内存空间直接构造(需C++20及以上支持std::construct_at):
#include <memory> void CreateTheClassInstance(TheClass* obj) { std::construct_at(obj, "specific args", specific_int); }
使用时用std::optional存储未初始化的对象:
#include <optional> SomethingElse() { CreateTheClassInstance(&_the_class.emplace()); } std::optional<TheClass> _the_class;
3. 自定义移动构造函数
如果TheClass的其他成员支持移动,可以手动实现移动构造函数——std::mutex无法直接移动,但可以为新对象创建新的mutex,同时转移其他成员的所有权:
class TheClass { public: // 原有构造函数... TheClass(TheClass&& other) noexcept : // 移动初始化其他成员 _mutex() // 为新对象创建新的mutex { // 按需处理其他资源的转移逻辑 } TheClass& operator=(TheClass&& other) noexcept { if (this != &other) { // 移动其他成员 // 确保原对象处于可析构的安全状态 } return *this; } private: std::mutex _mutex; // 其他成员 };
内容的提问来源于stack exchange,提问作者intrigued_66
相关产品推荐
相关产品推荐

