menu

hjk41的日志

Avatar

Effective C++ 31: Never return a reference to a local object or a dereferenced pointer...

Item 31: Never return a reference to a local object or to a dereferenced pointer initialized by new within the function.

The first part seems apparent. Local objects are destructed when they go out of scope, which means the returnd references will point to nothing.

The second part requires further discussion, though. Personally, I don't like the idea of returning a pointer to an object initialized within a function, because the client may forget to delete the object. However, some libraries ( like the Probability Network Library of Intel ) do return pointers in member functions. And returning a pointer sometimes ,for example, when we are constructing objects, makes things simpler. The constructors can never be declared virtual, while other member functions can. This may be quite useful when we are constructing objects whose class we don't know in advance.

评论已关闭