How to convert template T to a class pointer - c++

I am trying to implement a template Array class that can hold pointers as well as primitive data types.
But when calling the destructor, the pointers in that array are not properly deleting.
So I am trying to convert each item in that array to its corresponding class and call delete. But I met with an issue. I'm not able to convert T type to my class pointer.
My intention is to delete items in that array. Can someone please help in this?
template <class T>
class LIBRARY_EXPORT MyArrayT
{
public:
MyArrayT()
{
this->count = 0;
}
~MyArrayT()
{
if ((this->count) > 0)
{
//std::cout << "Deleting Array values" << std::endl;
delete[] this->values;
//free(this->values);
/*for (int i = 0; i < this->count; i++)
{
delete this->values[i];
}*/
this->count = 0;
}
}
void SetValue(std::vector< T > items)
{
//Delete existing memory
delete[] this->values;
this->count = items.size();
if (this->count > 0)
{
this->values = new T[this->count];
for (int i = 0; i < count; i++)
{
this->values[i] = items[i];
}
}
}
void SetValue(T items, int index)
{
if (this->count > index)
{
this->values[index] = items;
}
}
T GetValue(int index)
{
if (this->count > index)
{
return this->values[index];
}
return NULL;
}
T* GetValue()
{
return this->values;
}
_int64 GetCount()
{
return this->count;
}
private:
_int64 count;
T* values;
};
class LIBRARY_EXPORT MyString
{
public:
MyString();
~MyString();
void SetValue(std::string str);
std::string GetValue();
_int64 GetCount();
private:
_int64 count;
char* value;
};
int main()
{
MyArrayT<MyString*>* MyArrayValue = new MyArrayT<MyString*>() ;
vector<MyString*> value9;
MyString* opt1 = new MyString();
opt1->SetValue("Option: 1");
value9.push_back(opt1);
MyArrayValue->SetValue(value9);
MyArrayT<int>* MyArrayValueInt = new MyArrayT<int>() ;
vector<int> value1;
value1.push_back(1);
value1.push_back(2);
MyArrayValueInt->SetValue(value1);
delete MyArrayValue; //Calling this delete doesn't calling the ~MyString() destructor
delete MyArrayValueInt;
}

Related

Still having an Unhandled Exception after editing it a bit

Inventory::Inventory()
{
this->cap = 10;
this->nrOfItems = 0;
this->itemArr = new Item* [cap]();
}
Inventory::~Inventory()
{
for (size_t i = 0; i < this->nrOfItems; i++)
{
delete this->itemArr[i];
}
delete[] this->itemArr;
}
void Inventory::expand()
{
this->cap *= 2;
Item **tempArr = new Item*[this->cap]();
for (size_t i = 0; i < this->nrOfItems, i++;)
{
tempArr[i] = new Item(*this->itemArr[i]);
}
for (size_t i = 0; i < this->nrOfItems, i++;)
{
delete this->itemArr[i];
}
delete[] this->itemArr;
this->itemArr = tempArr;
this->initialize(this->nrOfItems);
}
void Inventory::initialize(const int from)
{
for (size_t i = from; i < cap, i++;)
{
this->itemArr[i] = nullptr;
}
}
void Inventory::addItem(const Item& item)
{
if (this->nrOfItems >= this->cap)
{
expand();
}
this->itemArr[this->nrOfItems++] = new Item(item);
}
void Inventory::removeItem(int index)
{
}
Above is my code from Inventory.cpp and the issue is that I keep getting an Unhandled Exception from the line that has:
this->itemArr[i] = nullptr;
I have no idea where I'm messing up in the code. Below I am posting from Inventory.h:
class Inventory
{
private:
int cap;
int nrOfItems;
Item **itemArr;
void expand();
void initialize(const int from);
public:
Inventory();
~Inventory();
void addItem(const Item &item);
void removeItem(int index);
inline void debugPrint() const
{
for (size_t i = 0; i < this->nrOfItems; i++)
{
std::cout << this->itemArr[i]->debugPrint() << std::endl;
}
}
};
This is where itemArr should be housed but for some reason, it is not pulling. I am new to coding so I don't know all of the tips and tricks involved with it.
In the loop i < cap, i++;, you will first check if i is in bounds, and then increase it by one before the loop body executes. Thus if i=cap-1 the check will pass, i will become cap and you're out of bounds.
Instead write (size_t i = from; i < cap;i++), so that the increment of i is executed after the loop body.
A see several problems with your code:
In Inventory::expand(), since you are working with an array of pointers (why not an array of objects?), there is no need to make clones of the existing Item objects to the new array, just copy the existing pointers as-is. You are just expanding the array to fit more pointers, so the clones are wasted overhead. Not a fatal issue, but it is something you should be aware of.
In both Inventory::initialize() and Inventory::expand(), your loops are setup incorrectly. You are performing the i++ in the wrong place. Given this definition of a loop:
for ( <init-statement> <condition> ; <iteration_expression> )
You are performing the i++ as part of the <condition>, not the <iteration_expression>. A simply typo caused by you using the comma operator instead of ;, but an important typo nonetheless.
Inventory is violating the Rule of 3/5/0, by not implementing copy/move constructors and copy.move assignment operators.
With that said, try this instead:
class Inventory
{
private:
size_t cap;
size_t nrOfItems;
Item **itemArr;
void expand();
public:
Inventory();
Inventory(const Inventory &src);
Inventory(Inventory &&src);
~Inventory();
Inventory& operator=(Inventory rhs);
void addItem(const Item &item);
void removeItem(size_t index);
inline void debugPrint() const
{
for (size_t i = 0; i < nrOfItems; ++i)
{
std::cout << itemArr[i]->debugPrint() << std::endl;
}
}
};
Inventory::Inventory()
{
cap = 10;
nrOfItems = 0;
itemArr = new Item*[cap]();
}
Inventory::Inventory(const Inventory &src)
{
cap = src.cap;
nrOfItems = src.nrOfItems;
itemArr = new Item*[cap]();
for(size_t i = 0; i < nrOfItems; ++i)
{
itemArr[i] = new Item(*(src.itemArr[i]));
}
}
Inventory::Inventory(Inventory &&src)
{
cap = src.cap; src.cap = 0;
nrOfItems = src.nrOfItems; src.nrOfItems = 0;
itemArr = src.itemArr; src.itemArr = nullptr;
}
Inventory::~Inventory()
{
for (size_t i = 0; i < nrOfItems; ++i)
{
delete itemArr[i];
}
delete[] itemArr;
}
Inventory& Inventory::operator=(Inventory rhs)
{
Inventory temp(std::move(rhs));
std::swap(cap, temp.cap);
std::swap(nrOfItems, temp.nrOfItems);
std::swap(itemArr, temp.itemArr);
return *this;
}
void Inventory::expand()
{
size_t newCap = cap * 2;
Item **tempArr = new Item*[newCap]();
for (size_t i = 0; i < nrOfItems; ++i)
{
tempArr[i] = itemArr[i];
}
delete[] itemArr;
itemArr = tempArr;
cap = newCap;
}
void Inventory::addItem(const Item& item)
{
if (nrOfItems >= cap)
{
expand();
}
itemArr[nrOfItems] = new Item(item);
++nrOfItems;
}
void Inventory::removeItem(size_t index)
{
if (index < nrOfItems)
{
Item *item = itemArr[index];
for(size_t i = index + 1; i < nrOfItems; ++i)
{
itemArr[i-1] = itemArr[i];
}
--nrOfItems;
itemArr[nrOfItems] = nullptr;
delete item;
}
}
That being said, you really should be using std::vector instead, let it handle these details for you, eg:
#include <vector>
class Inventory
{
private:
std::vector<Item> itemVec;
public:
Inventory();
void addItem(const Item &item);
void removeItem(size_t index);
inline void debugPrint() const
{
for (Item &item : items)
{
std::cout << item.debugPrint() << std::endl;
}
}
};
Inventory::Inventory()
{
itemVec.reserve(10);
}
void Inventory::addItem(const Item& item)
{
itemVec.emplace_back(item);
}
void Inventory::removeItem(size_t index)
{
if (index < itemVec.size())
{
itemVec.erase(itemVec.begin() + index);
}
}
See how much simpler that is? :)

Segmentation fault when using copy constructor C++

Everything seems to be copying fine, but when I call array2.print(), it shows segmentation fault. What am I doing wrong?
#include <iostream>
#include <initializer_list>
template <typename T>
class DynamicArray
{
private:
const int GROWTH_FACTOR = 2;
const int INITIAL_CAPACITY = 5;
T *m_array;
int m_capacity; // Capacity of the array
int m_size; // Number of added elements
public:
DynamicArray(std::initializer_list<T> elements)
: m_size(elements.size())
, m_capacity(elements.size() * 2)
{
m_array = new T[m_capacity];
std::copy(elements.begin(), elements.end(), m_array);
}
DynamicArray()
: m_size(0)
, m_capacity(INITIAL_CAPACITY)
{
m_array = new T[m_capacity];
}
~DynamicArray()
{
delete[] m_array;
}
DynamicArray(const DynamicArray& other)
: GROWTH_FACTOR(other.GROWTH_FACTOR)
, INITIAL_CAPACITY(other.INITIAL_CAPACITY)
, m_capacity(other.m_capacity)
, m_size(other.m_size)
{
T *m_array = new T[m_capacity];
std::copy(other.m_array, other.m_array + m_size, m_array);
}
int size()
{
return m_size;
}
int capacity()
{
return m_capacity;
}
void resize()
{
int new_capacity = m_capacity * GROWTH_FACTOR;
m_capacity = new_capacity;
T *temp = new T[new_capacity];
std::copy(m_array, m_array + m_capacity, temp);
delete[] m_array;
m_array = temp;
}
void deleteAt(int pos)
{
for (int i = pos; i < m_size - 1; i++)
{
(*this)[i] = (*this)[i + 1];
}
m_size--;
}
void insertAt(T value, int pos)
{
if (m_capacity == m_size)
{
resize();
}
for (int i = m_size - 1; i >= pos; i--)
{
(*this)[i + 1] = (*this)[i];
}
m_size++;
(*this)[pos] = value;
}
void append(T value)
{
insertAt(value, m_size);
}
void print() {
for (int i = 0; i < m_size; i++)
{
std::cout << (*this)[i] << ", ";
}
std::cout << std::endl;
}
T& operator[](int index)
{
if (index < 0 || index > m_size - 1)
{
throw std::invalid_argument("Index out of range!");
}
return m_array[index];
}
};
int main()
{
DynamicArray<int> array = { 1, 2, 3, 4 };
DynamicArray<int> array2 = array;
array2.print();
return 0;
}
The error is here
T *m_array = new T[m_capacity];
It should be
m_array = new T[m_capacity];
By declaring a new variable called m_array you hid the class member variable that you wanted to assign to. The technical name for this is shadowing, a good compiler would warn you about this.
You redeclare m_array in the cctor, which shadows the class member.

Memory Leakage while using dynamic array pointer in C++

As the title reads, I get memory leakage when I run my program. However, I think the problem is that I do not tell the destructor to free all of the memory when the program is done. But the problem is that the program crashes when I try to put my freeMemory() function in the destructor. The compiler says that the function getString() in my base class could not read from string. I wonder if you can see the problem, because I surely can not... And to not get too many rows of code, I will only post the functions which could be the possible source of leakage. Handler.h:
class Handler {
private:
Competitor* *person;
int capacity;
int nrOfCompetitors;
void expand();
void initiate(int start) const;
int find(string name) const;
void freeMemory();
public:
Handler(int capacity = 3);
Handler(const Handler & origObj);
virtual ~Handler();
Handler operator=(const Handler & origObj);
bool addExerciser(string name, string gender, int age);
bool addProffs(string name, string gender, string compound, int nrOfSeasons);
void getCompetitors(string arr[]) const;
int getNrOfCompetitors() const;
void getProffs(string arr[]) const;
int getNrOfProffs() const;
void getExercisers(string arr[]) const;
int getNrOfExercisers() const;
bool removeCompetitor(string name);
bool changeNrOfSeasons(string name, int newNrOfSeasons) const;
void sortCompetitors();
};
Handler.cpp (just the relevant functions):
void Handler::expand() {
this->capacity += 5;
Competitor* *tmp = new Competitor*[capacity];
for (int i = 0; i < this->nrOfCompetitors; i++) {
tmp[i] = this->person[i];
}
delete[] this->person;
this->person = tmp;
this->initiate(nrOfCompetitors);
}
void Handler::initiate(int start) const {
for (int i = start; i < this->capacity; i++) {
person[i] = nullptr;
}
}
void Handler::freeMemory() {
for (int i = 0; i < nrOfCompetitors; i++) {
delete person[i];
}
delete[] person;
}
Handler::Handler(int capacity) {
this->capacity = capacity;
this->nrOfCompetitors = 0;
this->person = new Competitor*[this->capacity];
initiate(0);
}
Handler::Handler(const Handler & origObj) {
this->capacity = origObj.capacity;
this->nrOfCompetitors = origObj.nrOfCompetitors;
this->person = new Competitor*[origObj.capacity];
for (int i = 0; i < this->capacity; i++) {
person[i] = origObj.person[i];
}
initiate(nrOfCompetitors);
}
Handler::~Handler() {
//freeMemory();
delete[] person;
}
Handler Handler::operator=(const Handler & origObj) {
if (this != &origObj) {
freeMemory();
this->capacity = origObj.capacity;
this->nrOfCompetitors = origObj.nrOfCompetitors;
this->person = new Competitor*[origObj.capacity];
for (int i = 0; i < this->capacity; i++) {
person[i] = origObj.person[i];
}
initiate(nrOfCompetitors);
}
return *this;
}
bool Handler::removeCompetitor(string name) {
bool removed = false;
int found = find(name);
if (found != -1) {
delete person[found];
for (int i = found; i < nrOfCompetitors; i++) {
person[found] = person[found + 1];
}
delete person[nrOfCompetitors];
nrOfCompetitors -= 1;
removed = true;
}
return removed;
}
void Handler::sortCompetitors() {
Competitor* tmp;
bool swap;
do {
swap = false;
for (int i = 0; i < nrOfCompetitors - 1; i++) {
if (person[i]->getName() > person[i + 1]->getName()) {
tmp = person[i];
person[i] = person[i + 1];
person[i + 1] = tmp;
swap = true;
}
}
} while (swap);
}
EDIT:
When the program crashes while I am trying to use the freeMemory() function in my destructor, the compiler says that the getString() function in my base class could not read character from string.
Competitor.h (base class):
string getString() const;
virtual string getSpecificString() const = 0;
Competitor.cpp:
string Deltagare::getString() const {
return "Name: " + this->name + "\nGender: " + this->gender + "\n" + this->getSpecificString();
}
Exerciser.h (sub class):
virtual string getSpecificString() const;
Exerciser.cpp
string Exerciser::getSpecificString() const {
return "Age: " + to_string(this->age);
}
Solved! Solution:
The problems were in the destructor, assignment operator and the copy-constructor, but they are fixed now. I used a clone method because I was not able to type person[i] = new Competitor[origObj.person[i]] because of the fact that the Competitor class is an abstract class.
Competitor.h:
virtual Competitor* clone() const = 0;
Exerciser.h:
Exerciser* clone() const;
Exerciser.cpp:
Exerciser * Exerciser::clone() const {
return new Exerciser(*this);
}
Edit in the copy-constructor and the assignment operator:
this->person = new Competitor*[origObj.capacity];
for (int i = 0; i < origObj.nrOfCompetitors; i++) {
person[i] = origObj.person[i]->clone();
}
Edit in the destructor:
Handler::~Handler() {
freeMemory();
}

Minimal C++ STL Vector Implementation Problems

I have a technical problem and it's really confusing me. I apologise in advance because I may not be giving the relevant details; I don't yet why it's going wrong and it would be excessive to include all the code I'm working with.
I'm working with a large program that uses the C++ STL. I'm moving this code to a very sensitive environment without a standard clib nor STL implementaton; it will redefine malloc/free/new/delete etc... For that, I need to replace the std:: parts with my own simplified implementations. I've started with std::vector. Right now it's running in the standard ecosystem so it's the GNU libc and STL. The only thing that's changed is this vector class.
When I execute the program with the replaced class, it segfaults. I've put this through GDB and found that the program will request an object from the vector using the subscript operator. When the object reference is returned, a method is invoked and the program segfaults. It seems it can't find this method and ends up in main_arena() in GDB. The type of the object is an inherited class.
I'm really not sure at all what the problem is here. I would love to provide additional details, but I'm not sure what more I can give. I can only assume something is wrong with my vector implementation because nothing else in the program has been changed. Maybe there's something obvious that I'm doing wrong here that I'm not seeing at all.
I'm using: g++ (GCC) 4.4.5 20110214 (Red Hat 4.4.5-6)
I'd really appreciate any feedback/advice!
#ifndef _MYSTL_VECTOR_H_
#define _MYSTL_VECTOR_H_
#include <stdlib.h>
#include <assert.h>
typedef unsigned int uint;
namespace mystl
{
/******************
VECTOR
********************/
template <typename T>
class vector
{
private:
uint _size;
uint _reserved;
T *storage;
void init_vector(uint reserve)
{
if (reserve == 0)
{
_reserved = 0;
return;
}
storage = (T*)malloc(sizeof(T)*reserve);
assert(storage);
_reserved = reserve;
}
public:
vector()
{
// std::cerr << "default constructor " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
}
vector(const vector<T> &other)
{
// std::cerr << "copy constructor " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
init_vector(other.size());
_size = other.size();
for (uint i=0; i<other.size(); i++)
{
storage[i] = T(other[i]);
}
}
vector(uint init_num, const T& init_value)
{
// std::cerr << "special constructor1 " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
init_vector(init_num);
for (size_t i=0; i<init_num; i++)
{
push_back(init_value);
}
}
vector(uint init_num)
{
// std::cerr << "special constructor2 " << this << std::endl;
storage = NULL;
_size = 0;
_reserved = 0;
init_vector(init_num);
}
void reserve(uint new_size)
{
if (new_size > _reserved)
{
storage = (T*)realloc(storage, sizeof(T)*new_size);
assert(storage);
_reserved = new_size;
}
}
void push_back(const T &item)
{
if (_size >= _reserved)
{
if (_reserved == 0) _reserved=1;
reserve(_reserved*2);
}
storage[_size] = T(item);
_size++;
}
uint size() const
{
return _size;
}
~vector()
{
if (_reserved)
{
free(storage);
storage = NULL;
_reserved = 0;
_size = 0;
}
}
// this is for read only
const T& operator[] (unsigned i) const
{
// do bounds check...
if (i >= _size || i < 0)
{
assert(false);
}
return storage[i];
}
T& operator[] (unsigned i)
{
// do bounds check...
if (i >= _size || i < 0)
{
assert(false);
}
return storage[i];
}
// overload = operator
const vector<T>& operator= (const vector<T>& x)
{
// check for self
if (this != &x)
{
_reserved = 0;
_size = 0;
storage = NULL;
init_vector( x.size() );
for(uint i=0; i<x.size(); i++)
{
storage[i] = T(x[i]);
}
_size = x.size();
}
return *this;
}
uint begin() const
{
return 0;
}
void insert(uint pos, const T& value)
{
push_back(value);
if (size() == 1)
{
return;
}
for (size_t i=size()-2; i>=pos&& i>=0 ; i--)
{
storage[i+1] = storage[i];
}
storage[pos] = value;
}
void erase(uint erase_index)
{
if (erase_index >= _size)
{
return;
}
//scoot everyone down by one
for (uint i=erase_index; i<_size; i++)
{
storage[i] = storage[i+1];
}
_size--;
}
void erase(uint start, uint end)
{
if (start > end)
{
assert(false);
}
if (end > _size)
end = _size;
for (uint i=start; i<end; i++)
{
erase(start);
}
assert(false);
}
void clear()
{
erase(0,_size);
}
bool empty() const
{
return _size == 0;
}
}; //class vector
}
#endif // _MYSTL_VECTOR_H_
Wow!
Your assignment operator also leaks memory.
Becuause you are using malloc/release the constructor to your type T will will not be called and thus you can not use your vector for anything except the most trivial of objects.
Edit:
I am bit bored this morning: Try this
#include <stdlib.h> // For NULL
#include <new> // Because you need placement new
// Because you are avoiding std::
// An implementation of swap
template<typename T>
void swap(T& lhs,T& rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
template <typename T>
class vector
{
private:
unsigned int dataSize;
unsigned int reserved;
T* data;
public:
~vector()
{
for(unsigned int loop = 0; loop < dataSize; ++loop)
{
// Because we use placement new we must explicitly destroy all members.
data[loop].~T();
}
free(data);
}
vector()
: dataSize(0)
, reserved(10)
, data(NULL)
{
reserve(reserved);
}
vector(const vector<T> &other)
: dataSize(0)
, reserved(other.dataSize)
, data(NULL)
{
reserve(reserved);
dataSize = reserved;
for(unsigned int loop;loop < dataSize;++loop)
{
// Because we are using malloc/free
// We need to use placement new to add items to the data
// This way they are constructed in place
new (&data[loop]) T(other.data[loop]);
}
}
vector(unsigned int init_num)
: dataSize(0)
, reserved(init_num)
, data(NULL)
{
reserve(reserved);
dataSize = reserved;
for(unsigned int loop;loop < dataSize;++loop)
{
// See above
new (&data[loop]) T();
}
}
const vector<T>& operator= (vector<T> x)
{
// use copy and swap idiom.
// Note the pass by value to initiate the copy
swap(dataSize, x.dataSize);
swap(reserved, x.rserved);
swap(data, x.data);
return *this;
}
void reserve(unsigned int new_size)
{
if (new_size < reserved)
{ return;
}
T* newData = (T*)malloc(sizeof(T) * new_size);
if (!newData)
{ throw int(2);
}
for(unsigned int loop = 0; loop < dataSize; ++loop)
{
// Use placement new to copy the data
new (&newData[loop]) T(data[loop]);
}
swap(data, newData);
reserved = new_size;
for(unsigned int loop = 0; loop < dataSize; ++loop)
{
// Call the destructor on old data before freeing the container.
// Remember we just did a swap.
newData[loop].~T();
}
free(newData);
}
void push_back(const T &item)
{
if (dataSize == reserved)
{
reserve(reserved * 2);
}
// Place the item in the container
new (&data[dataSize++]) T(item);
}
unsigned int size() const {return dataSize;}
bool empty() const {return dataSize == 0;}
// Operator[] should NOT check the value of i
// Add a method called at() that does check i
const T& operator[] (unsigned i) const {return data[i];}
T& operator[] (unsigned i) {return data[i];}
void insert(unsigned int pos, const T& value)
{
if (pos >= dataSize) { throw int(1);}
if (dataSize == reserved)
{
reserve(reserved * 2);
}
// Move the last item (which needs to be constructed correctly)
if (dataSize != 0)
{
new (&data[dataSize]) T(data[dataSize-1]);
}
for(unsigned int loop = dataSize - 1; loop > pos; --loop)
{
data[loop] = data[loop-1];
}
++dataSize;
// All items have been moved up.
// Put value in its place
data[pos] = value;
}
void clear() { erase(0, dataSize);}
void erase(unsigned int erase_index) { erase(erase_index,erase_index+1);}
void erase(unsigned int start, unsigned int end) /* end NOT inclusive so => [start, end) */
{
if (end > dataSize)
{ end = dataSize;
}
if (start > end)
{ start = end;
}
unsigned int dst = start;
unsigned int src = end;
for(;(src < dataSize) && (dst < end);++dst, ++src)
{
// Move Elements down;
data[dst] = data[src];
}
unsigned int count = start - end;
for(;count != 0; --count)
{
// Remove old Elements
--dataSize;
// Remember we need to manually call the destructor
data[dataSize].~T();
}
}
unsigned int begin() const {return 0;}
}; //class vector
With your current memory handling, this vector would only work with plain old data types.
To handle all types, it must ensure that objects
are actually created (malloc doesn't do that),
destroyed (free doesn't do that),
and you can't reallocate memory with realloc, because complex objects are not guaranteed to remain valid if they are byte-wise copied to another location.
Looks like the answer can be found in your question: "When the object reference is returned, a method is invoked and the program segfaults. It seems it can't find this method and ends up in main_arena() in GDB. The type of the object is an inherited class."
You probably store base class instance T in the vector, but make push_back for the instance of the class inherited from T. In push_back {storage[_size] = T(item);} you cast (actually make copy constructor T:T(const T&)) item to T (this probably named 'type cut'), then get reference to T and invoke a method of the class inherited from T using virtual table of T where the method is not defined yet/abstract. Am I right?
To make it properly work you should put T* in the vector or shared_ptr/unique_ptr depending on the ownership terms you apply to vector elements.
Generally in vector you can store only POD (Plain Old Data) types.

qsorting an array of class pointers

I've read a lot of material on how to do this. Unfortunately, they all resort to using something other than qsort (sort, usually). However, this is impossible for me as I'm not allowed to use anything from the algorithm library. I have to implement this from scratch, pretty much. What I've got:
class String {
public:
char* string;
int size;
String(char* string=0, int size=0) {
this->string = string;
this->size = size;
}
~String() {
delete [] string;
}
};
int compare(void* obj1, void* obj2) {
String* str1 = ((String*) obj1)->getColumn(column);
String* str2 = ((String*) obj2)->getColumn(column);
int i = strcmp(str1->string, str2->string);
delete str1;
delete str2;
return i;
}
class ArrayList {
int count;
int arraySize;
public:
String** list;
ArrayList() {
count = 0;
arraySize = 10;
list = new String*[arraySize];
}
~ArrayList() {
while(size()) {
delete remove();
}
}
void add(String* s) {
if(count==arraySize)
grow();
list[count++] = s;
}
String* remove() {
return list[count--];
}
String* get(int i) {
return list[i];
}
int size() {
return count;
}
private:
void grow() {
String** temp = new String*[arraySize*=2];
for(int i=0; i<count; i++) {
temp[i] = list[i];
}
delete [] list;
list = temp;
}
};
And my (current) call to qsort, though I've tried many combinations:
qsort(list->list, list->size, sizeof(String**), compare);
The error I ALWAYS get, not matter what I pass:
argument of type ‘int (ArrayList::)()’ does not match ‘size_t’
The code I've copied here doesn't include everything, but I've verified that all of the pieces work as intended, so don't worry about missing methods and such.
You have used list->size instead of list->size(). The code should be:
qsort(list->list, list->size(), sizeof(String**), compare);