From: ArbolOne on 27 Feb 2010 08:15 Hello boys and girls! My function returns a smart pointer as follows const Onelib::MySmartPointer<Twolib::someMethod1>& MyClass::someMethod2(){...} This function works OK, however, someone told me that it was not a wise idea to return a smart pointer by const &. It was not possible to ask what was meant by the comment or what better solution would be there. So, I am asking here. Any body?
From: Alf P. Steinbach on 27 Feb 2010 08:36 * ArbolOne: > Hello boys and girls! > My function returns a smart pointer as follows > const Onelib::MySmartPointer<Twolib::someMethod1>& > MyClass::someMethod2(){...} > > This function works OK, however, someone told me that it was not a > wise idea to return a smart pointer by const &. > It was not possible to ask what was meant by the comment or what > better solution would be there. So, I am asking here. Any body? Returning 'T const&' is an optimization. It has a cost, namely that the object that you're returning a reference to, here a MySmartPointer, must continue to exist. And that in turn restricts the implementation of the function and perhaps the class it's part of, if it is (apparently, above it is a member function). For example, this function has Undefined Behavior: int const& foo() { return 666; } It may appear to work, but will fail at the most inconvenient & embarassing time. So as a general default rule one should not return 'T&'. But this is a rule with a great many exceptions. It's difficult/~impossible to say whether any of those exceptions to the general rule applies in your case. Whether the 'const' is meaningful or not may depend on the smart pointer type. For example, with std::auto_ptr a 'const' prevents ownership transfer and so can be useful for a locally declared variable (it's an idiom), but for that same reason is generally meaningless and absurd for a std::auto_ptr function result -- you can then dereference the result but not store it anywhere. And as an always-meaningless example, with a boost::shared_ptr a 'const' is meaningless because a copy of the smart pointer can always be constructed and used to change the referent's reference count and/or the common custom deleter. Cheers & hth., - Alf
|
Pages: 1 Prev: What's up with this struct problem Next: What does this mean? |