C++:类中用初始化列表初始化动态set指针成员的方法
如何用初始化列表初始化std::set指针成员?
嘿,我懂你遇到的麻烦——当类成员是std::set<...>*而不是直接的对象时,确实没法像非指针成员那样直接用初始化列表赋值。别担心,咱们只需要多一步内存分配的操作就能搞定,直接看代码和解释:
第一步:实现带初始化列表的构造函数
你需要在构造函数的成员初始化列表里,先通过new为StringSet_分配内存,同时把传入的初始化列表直接传给std::set的构造函数,这样就能一次性完成指针分配和内部set的初始化:
Textpool::Textpool(const std::initializer_list<std::experimental::string_view>& StringList) : StringSet_(new std::set<std::experimental::string_view>(StringList)) { // 这里不需要额外代码,初始化已经在成员列表里完成了 }
第二步:修复析构函数,避免内存泄漏
因为你用了new分配内存,默认的=default析构函数不会帮你释放这块内存,所以必须手动实现析构函数:
Textpool::~Textpool() { delete StringSet_; }
重要补充:处理拷贝/赋值的问题
如果不处理拷贝构造和拷贝赋值运算符,默认的浅拷贝会导致多个Textpool对象指向同一个set,最后析构时重复delete造成崩溃。你有两种选择:
- 禁用拷贝操作(如果你的类不需要被拷贝):
class Textpool { public: Textpool() = default; Textpool(const std::initializer_list<std::experimental::string_view>& StringList); ~Textpool(); // 禁用拷贝构造和赋值 Textpool(const Textpool&) = delete; Textpool& operator=(const Textpool&) = delete; private: std::set<std::experimental::string_view>* StringSet_ = nullptr; // 建议初始化指针为nullptr }; - 实现深拷贝(如果需要支持拷贝):
Textpool::Textpool(const Textpool& other) : StringSet_(new std::set<std::experimental::string_view>(*other.StringSet_)) { } Textpool& Textpool::operator=(const Textpool& other) { if (this != &other) { // 防止自赋值 delete StringSet_; StringSet_ = new std::set<std::experimental::string_view>(*other.StringSet_); } return *this; }
额外小建议
最好把指针成员StringSet_在类里初始化为nullptr,这样即使默认构造函数被调用,指针也不会是野指针,更安全。
内容的提问来源于stack exchange,提问作者Bazyli Polednia
相关产品推荐
相关产品推荐

