ars
ars

Reputation: 707

Exception safety constructor

In my small programm i need to have a class with some dynamic allocated data, like this one:

class MyClass
{
public:
  MyClass(size_t aSize1, size_t aSize2)
    :mX1(new char[aSize1]),
    mX2(new char[aSize2])
  {}
  ~MyClass()
  {
    delete[] mX1;
    delete[] mX2;
  }
...
private:
  MyClass(const MyClass& aObj);
  MyClass& operator=(const MyClass& aObj);

private:
  char* mX1;
  char* mX2;
};

The first question is, if i ought to use raw pointers, is the constructor of my class exception safety? I mean, is there any toruble in case if new throws an exception when allocating memory for mX2? In this case memory, that already allocated to mX1 will leak or correctly deleted?

The second question is, what will be better - to use some smart pointer (e.g. unique_ptr) or to use stl container (e.g. vector) to hold dynamic array?

UPD. If i'll use unique_ptr, std::unique_ptr<char[]> mX1; how should i implement copy constructor?

Upvotes: 0

Views: 151

Answers (1)

Ed Heal
Ed Heal

Reputation: 59987

  1. It is a good idea to handle exceptions in constructors. But when you have ran out of memory you are up a certain creek without a certain instrument. There is little you can do.
  2. Use smart pointers/vectors etc. Takes the hassle out of life.

Upvotes: 1

Related Questions