Home
121.
I need a vector of pointers. Should I choose auto_ptr as the object type to be held in the vector?

As a rule, you should never use std::auto_ptr. It is deprecated. A single copy or assignment operation can render the source object unusable.

122.
What two operators does a class always need to load to be called a smart pointer class?

The following: operator* and operator->. They help use objects of the class with regular pointer semantics.

123.
I have an application in which Class1 and Class2 hold member attributes that point to objects of the other's type. Should I use a reference-counted pointer in this scenario?

Probably you wouldn't because of the cyclic dependency that will keep the reference count from going down to zero and will consequently keep objects of the two classes permanently in the heap.

124.
A string class also dynamically manages character arrays on the free store. Is a string class therefore a smart pointer, too?

No, it isn't. These classes typically don't implement both operator* and operator-> and are therefore not classifiable as smart pointers.

125.
I see that I can use fstream for both writing and reading to a file, so when should I use ofstream and ifstream?

If your code or module needs to only be reading from a file, you should instead use ifstream. Similarly, if it needs to only write to a file use ofstream. In both cases fstream would work fine, but for the sake of ensuring data and code integrity, it is better to have a restrictive policy similar to using const, which is not compulsory either.

126.
When should I use cin.get(), and when should I use cin.getline()?

cin.getline() ensures that you capture the entire line including white spaces entered by the user. cin.get()helps you capture user input one character at a time.

127.
Why raise exceptions instead of returning an error?

You may not always have the privilege of returning an error. If a call to new fails, you need to handle exceptions thrown by new to prevent your application from crashing. Additionally, if an error is very severe and makes the future functioning of your application impossible, you should consider throwing an exception.

128.
Why should my exception class inherit from std::exception?

This is, of course, not compulsory, but it helps you reuse all those catch() blocks that already catch exceptions of type std::exception. You can write your own exception class that doesn’t inherit from anything else, but then you have to insert new catch(MyNewExceptionType&) statements at all the relevant points.

129.
I have a function that throws an exception. Does it need to be caught at the very same function?

Not at all. Just ensure that the exception type thrown is caught at one of the calling functions in the call stack.

130.
Can a constructor throw an exception?

Constructors actually have no choice! They don't have return values, and throwing an exception is the best way to demonstrate disagreement.