pass string by value because of "mean what you say"?
Hi!
I recently read the term "say what you mean, mean what you say"
frequently. This term is kind of new to me. I'm trying to apply it to a
common technique: passing std::strings by const&.
Given a class interface, which is purely virtual in order to show
different implementations for this discussion. See derived classes below.
struct Foo
{
virtual void setName(std::string const&) =0;
virtual std::string const& getName() const =0;
};
Ok, we observe a class that has some sort of "name" attribute. We may
set the attribute (I don't use the term "value" here!) and we may
retrieve it.
An obivous implementation would be:
struct SimpleFoo : Foo
{
void setName(std::string const& newName) { name = newName; }
std::string const& getName() const { return name; }
private:
std::string name;
};
Here I would observe the "std::string const& newName" argument type to
be an optimization for passing the value "newName". The object identity
of "newName" is never used. But the interface allows it. So one could
actually do the following:
struct BrokenFoo : Foo
{
void setName(std::string const& newName) { namePtr = newName; }
std::string const& getName() const { return *namePtr; }
private:
std::string namePtr;
};
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.
Wouldn't this follow the saying "say what you mean, mean what you say"
more strictly than a reference argument?
Frank
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]