Академический Документы
Профессиональный Документы
Культура Документы
5/26/12
Sourabh Agrawal
AGENDA
To suggest a approach to effective way of writing C++ which are more comprehensible, maintainable, portable, extensible, efficient, and likely to behave as you expect .
5/26/12
Sourabh Agrawal
Topics
List members in an initialization list in the order in which they are declared
Declare a copy constructor and an assignment operator for classes with dynamically allocated memory
5/26/12
Sourabh Agrawal
5/26/12
Sourabh Agrawal
class Empty { }; it's essentially the same as if you'd written this: class Empty { public: Empty() { }
5/26/12 ~Empty()
{}
Sourabh Agrawal
5/26/12
Sourabh Agrawal
5/26/12
Sourabh Agrawal
5/26/12
Sourabh Agrawal
template<class T> class Array { public: Array(int low, int high); //Constructor Declaration size_t size; elements in array vector<T> data; array data is stored int lBound, hBound; bound, higher bound Agrawal 5/26/12 Sourabh // No. of // the // lower
5/26/12
Sourabh Agrawal
class ABC { public: explicit ABC(int x) // Not allowing implicit casting of integer to ABC { } }; void function(ABC Object) {
5/26/12 Sourabh Agrawal
Declare a copy constructor and an assignment operator for classes with dynamically allocated memory
5/26/12
Sourabh Agrawal
class String { char *data; public: String::String(const char *value) { if (value) { data = new char[strlen(value) + 1]; strcpy(data, value); } } String::~String() { delete [] data; } };
int main()
5/26/12
b = a; // Both b and a data* are pointing to same memory location Memory Leak
5/26/12
Sourabh Agrawal
When you try to delete a derived class object through a base class pointer and the base class has a nonvirtual the results are undefined.
Polymorphic base classes should declare virtual destructors. If a class has any virtual functions, it should 5/26/12 Sourabh Agrawal have a virtual destructor.
5/26/12
Sourabh Agrawal
If you can detect an assignment to self at the top of your assignment operator(s), you can return right away, possibly saving a lot of work that you'd otherwise have to go through to implement assignment A more important reason for checking for assignment to self is to 5/26/12 Sourabh Agrawal ensure correctness.
5/26/12
Sourabh Agrawal
Destructors should never emit exceptions. If functions called in a destructor may throw, the destructor should catch any exceptions, then swallow them or terminate the program. If class clients need to be able to react to exceptions thrown during an 5/26/12 Sourabh Agrawal operation, the class should provide a
5/26/12
Sourabh Agrawal
5/26/12
Sourabh Agrawal