You could use a pointer instead of a reference if:
- Null is a valid return value
- You dynamically constructed something in the function, and the recipient becomes the owner. (In this case, you might consider returning a smart pointer such as std::unique_ptr or boost::shared_ptr.)
Regardless, you would not want to return either a pointer or a reference to a local variable.
int& something(int j){int* p = 0 ;return *p;}void main(){int& i = something(5);i = 7; // run-time error}
在上面的代码中,由于引用不能指向NULL,因此如果p指向NULL,那么便会产生异常。除非可以确保p一定产生了有效的数据。否则不要讲pointer作为引用的返回值。
https://stackoverflow.com/questions/7813728/pointer-vs-reference-return-types
