Re: pass string by value because of "mean what you say"?
Hi!
Neil Butterworth schrieb:
I assume you really mean:
struct BrokenFoo : Foo {
// note use of & operator
void setName(std::string const& newName) { namePtr = & newName; }
std::string const& getName() const { return *namePtr;
private:
std::string * namePtr; // now is a pointer
};
because if you don't, I don't understand your question
Well, yes, I actually meant this. SG also spotted this mistake of mine.
I'm sorry for the confusion. I don't know how that slipped through.
This will certainly break sooner or later, because someone will pass a
temporary variable to setName. This would be avoided with a signature
like "void setName(std::string newName)" because of pass-by-value.
No it wouldn't, because you would then have:
void setName( std::string newName) {
namePtr = & newName;
}
where newName ceases to exist after the setter terminates.
Well, yes, that is correct. I was aware of that. I tried to make a
different point. I'll try to explain myself again.
Given a method like:
void Foo::messWithString(std::string const&);
could tell me "I pass in a reference, the function might rely on object
identity", because if it didn't rely on the object identity, the string
could be passed by value instead. I argue this point to be an example of
"say what you mean, mean what you say".
I actually wrote code recently which takes const& and relies on object
identity. This is why I come up with this. There is one important
difference to the std::string: The references are references to abstract
type (polymorphic use), thus no temporary object can be passed. So the
referenced type makes a difference, doesn't it?
Regarding performance issues: the setName(std::string) function (no
reference) will most likely be optimized by the compiler (inline
function) thus the extra copy will be spared despite pass-by-value.
Frank
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]