I'm relatively new to programming and recently, while I was doing the assignment I came across a problem that I'm not sure how to cope with. I have an abstract class called IPrintable
and it represents printable objects. Class UnorderedSet
is an unordered set of IPrintable
objects, it is actually a dynamically allocated array of pointers to the IPrintable
objects. The problem is that this implementation bounds lifetime of objects that exist somewhere in memory and "elements" in my set. I'm aware that when those objects get destructed my pointers will point to the deallocated memory block. Can someone tell me how to manage it? The only idea that I can think of is to use a dynamically allocated array of shared smart pointers, but I'm not sure how to do that.
Maybe something like this?
std::shared_ptr<std::shared_ptr<ns1::IPrintable>> set
;
But how to get shared_ptr from the array? Can I use set[index]
?
class UnorderedSet:virtual public IPrintable
{
int* n;
int* i;
IPrintable** set;
public:
UnorderedSet(int n):n(new int(n)),i(new int(0)),set(new IPrintable*[n])
{
for (int j = 0; j < n; j++)
set[j] = nullptr; // I cant have set[j]= new IPrintable
because its abstract class
}
...
void insert(IPrintable* const iprt)
{
if (*i == *n)
this->add_capacity();// extends capacity
set[*i] = iprt;
(*i)++;
}
...
}
class IComparable:public IPrintable
{
virtual double compare_criteria()const = 0;
public:
virtual ~IComparable()=default;
std::strong_ordering operator<=>(const IComparable&)const;
};
class Complex: public IComparable
{
double *re, *im;
public:
...}
int main()
{
Complex* z=new Complex(1,1);
UnorderedSet uset(4);
uset.insert(z);
z->~Complex();// uset.set[0] points to the deallocated memory block
return 0;
}