Monday, April 7, 2008

Prefer initialization to assignment in constructors

(From Item 12 of Effective C++)
Consider a template for generating classes that allow a name to be associated with a pointer to an object of some type T:
    template
    class NamedPtr {
    public:
    NamedPtr(const string& initName, T *initPtr);
    ...
    private:
    string name;
    T *ptr;
    };

(In light of the aliasing that can arise during the assignment and copy construction of objects with pointer members ( see Item 11), you might wish to consider whether
NamedPtr
should implement these function. Hint: it should (see Item 27).)

No comments: