Hi i am trying to understand how constructors work and so reading different examples. I have a class constructor that takes an initializer_list but it keeps giving Segmentation fault. The files that i have are as follows:
- 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;
}
My question is how can i resolve this issue and why am i getting this Segmentation fault and what does it mean so that i can avoid it in the future?
PS: I know that the error is due to the StrVec(std::initializer_list<std::string> il); constructor since if i remove this and its use in the mainfile.cpp then Segmentation fault goes away.
StrVec(std::initializer_list<std::string> il);constructor since if i remove this and its use in the mainfile.cpp then Segmentation fault goes awaypush_backand there's no way we can try this ourselves.StrVec(std::initializer_list<std::string> il);calls only one functionpush_backand you didn't provide your implementation for it