【发布时间】:2021-03-15 04:48:41
【问题描述】:
您好,我想了解构造函数的工作原理,并阅读不同的示例。我有一个类构造函数,它接受一个 initializer_list,但它不断给出Segmentation fault。我拥有的文件如下:
- strvec.h
class StrVec {
public:
StrVec(): elements(nullptr), first_free(nullptr), cap(nullptr) {
}
StrVec(const StrVec&);
StrVec(std::initializer_list<std::string> il);
StrVec &operator=(const StrVec&);
~StrVec();
void push_back(const std::string&);
void pop_back();
void reserve(std::size_t);
void resize(std::size_t, const std::string& = std::string());
bool empty() const {
return begin() == end();
}
std::size_t size() const {
return first_free - elements;
}
std::size_t capacity() const{
return cap - elements;
}
std::string *begin() const {
return elements;
}
std::string *end() const {
return first_free;
}
private:
static std::allocator<std::string> alloc;
void chk_n_alloc() {
if (size() == capacity()){
reallocate();
}
}
std::pair<std::string*, std::string*> alloc_n_copy(const std::string*, const std::string*);
void free();
void reallocate();
std::string *elements;
std::string *first_free;
std::string *cap;
};
- strvec.cpp
StrVec::StrVec(const StrVec &s){
auto newdata = alloc_n_copy(s.begin(), s.end());
elements = newdata.first;
first_free = cap = newdata.second;
}
StrVec::StrVec(std::initializer_list<std::string> il){
for(const auto &s:il){
push_back(s);
}
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string *b, const std::string *e){
auto data = alloc.allocate(e - b);
return {data, uninitialized_copy(b, e, data)};
}
void StrVec::push_back(const std::string& s){
chk_n_alloc();
alloc.construct(first_free++, s);
}
- mainfile.cpp
int main() {
StrVec sv10 { "il1", "il2", "il3", "il4", "il5" };
return 0;
}
我的问题是我该如何解决这个问题,为什么我会收到这个Segmentation fault,这是什么意思,以便我以后可以避免它?
PS:我知道错误是由 StrVec(std::initializer_list<std::string> il); 构造函数引起的,因为如果我删除它并在 mainfile.cpp 中使用它,那么 Segmentation fault 就会消失。
【问题讨论】:
-
请附上minimal reproducible example 以及您从调试器和地址清理器等工具中学到的东西。
-
我知道错误是由于
StrVec(std::initializer_list<std::string> il);构造函数,因为如果我删除它并在 mainfile.cpp 中使用它,那么分段错误就会消失 -
好的,但我们甚至不知道构造函数除了调用
push_back之外还做了什么,而且我们自己也无法尝试。 -
StrVec(std::initializer_list<std::string> il);只调用了一个函数push_back而你没有提供你的实现 -
我添加了 push_back() 成员。
标签: c++ c++11 segmentation-fault c++14