Читаем Thinking In C++. Volume 2: Practical Programming полностью

When writing code with exceptions, it’s particularly important that you always ask, "If an exception occurs, will my resources be properly cleaned up?" Most of the time you’re fairly safe, but in constructors there’s a particular problem: if an exception is thrown before a constructor is completed, the associated destructor will not be called for that object. Thus, you must be especially diligent while writing your constructor.

The general difficulty is allocating resources in constructors. If an exception occurs in the constructor, the destructor doesn’t get a chance to deallocate the resource. This problem occurs most often with "naked" pointers. For example:.

//: C01:Rawp.cpp

// Naked pointers

#include

using namespace std;

class Cat {

public:

  Cat() { cout << "Cat()" << endl; }

  ~Cat() { cout << "~Cat()" << endl; }

};

class Dog {

public:

  void* operator new(size_t sz) {

    cout << "allocating a Dog" << endl;

    throw 47;

  }

  void operator delete(void* p) {

    cout << "deallocating a Dog" << endl;

    ::operator delete(p);

  }

};

class UseResources {

  Cat* bp;

  Dog* op;

public:

  UseResources(int count = 1) {

    cout << "UseResources()" << endl;

    bp = new Cat[count];

    op = new Dog;

  }

  ~UseResources() {

    cout << "~UseResources()" << endl;

    delete [] bp; // Array delete

    delete op;

  }

};

int main() {

  try {

    UseResources ur(3);

  } catch(int) {

    cout << "inside handler" << endl;

  }

} ///:~

The output is the following:.

UseResources()

Cat()

Cat()

Cat()

allocating a Dog

inside handler

The UseResources constructor is entered, and the Cat constructor is successfully completed for the three array objects. However, inside Dog::operator new( ), an exception is thrown (to simulate an out-of-memory error). Suddenly, you end up inside the handler, without the UseResources destructor being called. This is correct because the UseResources constructor was unable to finish, but it also means the Cat objects that were successfully created on the heap were never destroyed.

<p>Making everything an object</p>

To prevent such resource leaks, you must guard against these "raw" resource allocations in one of two ways:

·         You can catch exceptions inside the constructor and then release the resource.

·         You can place the allocations inside an object’s constructor, and you can place the deallocations inside an object’s destructor.

Using the latter approach, each allocation becomes atomic, by virtue of being part of the lifetime of a local object, and if it fails, the other resource allocation objects are properly cleaned up during stack unwinding. This technique is called Resource Acquisition Is Initialization (RAII for short) , because it equates resource control with object lifetime. Using templates is an excellent way to modify the previous example to achieve this:.

//: C01:Wrapped.cpp

// Safe, atomic pointers

#include

using namespace std;

// Simplified. Yours may have other arguments.

template class PWrap {

  T* ptr;

public:

  class RangeError {}; // Exception class

  PWrap() {

    ptr = new T[sz];

    cout << "PWrap constructor" << endl;

  }

  ~PWrap() {

    delete [] ptr;

    cout << "PWrap destructor" << endl;

  }

  T& operator[](int i) throw(RangeError) {

    if(i >= 0 && i < sz) return ptr[i];

    throw RangeError();

  }

};

class Cat {

public:

  Cat() { cout << "Cat()" << endl; }

  ~Cat() { cout << "~Cat()" << endl; }

  void g() {}

};

class Dog {

public:

  void* operator new[](size_t) {

    cout << "Allocating a Dog" << endl;

    throw 47;

  }

  void operator delete[](void* p) {

    cout << "Deallocating a Dog" << endl;

    ::operator delete[](p);

  }

};

class UseResources {

  PWrap cats;

  PWrap dog;

public:

  UseResources() {

    cout << "UseResources()" << endl;

  }

  ~UseResources() {

    cout << "~UseResources()" << endl;

  }

  void f() { cats[1].g(); }

};

int main() {

  try {

    UseResources ur;

  } catch(int) {

    cout << "inside handler" << endl;

  } catch(...) {

    cout << "inside catch(...)" << endl;

  }

} ///:~

The difference is the use of the template to wrap the pointers and make them into objects. The constructors for these objects are called before the body of the UseResources constructor, and any of these constructors that complete before an exception is thrown will have their associated destructors called during stack unwinding.

The PWrap template shows a more typical use of exceptions than you’ve seen so far: A nested class called RangeError is created to use in operator[ ] if its argument is out of range. Because operator[ ] returns a reference, it cannot return zero. (There are no null references.) This is a true exceptional condition—you don’t know what to do in the current context, and you can’t return an improbable value. In this example, RangeError is simple and assumes all the necessary information is in the class name, but you might also want to add a member that contains the value of the index, if that is useful.

Now the output is:.

Cat()

Cat()

Cat()

PWrap constructor

allocating a Dog

~Cat()

~Cat()

~Cat()

PWrap destructor

inside handler

Перейти на страницу:

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных