This is the first time I have felt a smidgen of fear when learning C++. I am doing an exercise in Accelerated C++ and the fear is that I'm not appropriately handling memory. I'll list my code below but I figured I would give some specific questions first:
Is this statement correct: In memory, elements of an array are stored "against" each other (I think more precisely, contigious space is allocated for them?) and a pointer to an array points to the first element.
Are there any memory-specific issues that the below code will encounter?
If it interests me, would tools such as Valgrind worth looking into now, or should I wait until I have a better grasp of C++?
My "String List" is not complete, but are there any other glaring issues I might look into?
Accelerated C++ I have enjoyed thus far, everything has presented itself with ease, with this chapter the only one that has given me any difficulty. So here is the code:
String_list.h
#ifndef GUARD_STRING_LIST_H
#define GUARD_STRING_LIST_H
// String_list.h
#include <string>
// Store a list of strings
class String_list
{
public:
typedef std::string* iterator;
typedef const std::string* const_iterator;
String_list();
size_t size() const { return list_size; }
const_iterator begin() const { return first; }
const_iterator end() const { return last + 1; }
void push_back(std::string);
private:
iterator first;
iterator last;
size_t list_size;
};
#endif
String_list.cpp
#include <string>
#include "String_list.h"
String_list::String_list():list_size(0) {}
void String_list::push_back(std::string s) {
// allocate space for the updated list
std::string* updated_list = new std::string[list_size + 1];
// copy elements from list to updated list
for (size_t i = 0; i != list_size; ++i)
updated_list[i] = first[i];
// add new string to updated list
updated_list[list_size] = s;
// destroy array and free memory
if(list_size > 0)
delete[] first;
// update iterators
first = updated_list;
last = updated_list + list_size;
++list_size;
}