From: Mattias Flodin (flodin_at_[hidden])
Date: 2002-08-01 03:08:37
I had a quick look at the filesystem library headers and noticed this
comment in path.hpp:
// Rationale for returns of "const path" instead of "path"; see
// Scott Meyers, EC++, Item 21.
Now, that item says that operator+() and others returning a const object
is "The Right Thing To Do" because it prevents you from doing silliness
(a + b) = c
which is not allowed on native types and therefore, by extension, should
not be allowed on user-defined types.
This item is about operators. Class path returns const std::string from
leaf() and const path from branch(), both of which are ordinary member
functions not operators, so there is no correlation with native types
here to begin with.
I was going to complain about how this somewhat arbitrary restriction on
what the user can do with his temporary objects just gives the user a
hard time, without any benefits. But since I can't find any examples of
prevented usage that isn't obscure, I suppose I can live with it. It
also has the nice advantage that a switch to returning a reference isn't
as much of a catastrophy any longer (nobody will be mutating the
returned object, which means there will be no error later when
operations are attempted on the const ref). Unfortunately, code that
expects a reference to the returned value to remain constant after a
second call to leaf() would still fail if the return type was changed to
reference later on (otherwise, the entire ref-or-no-reference issue
could be left out of a standards document and be up to the implementor).
What I've been meaning to ask, after this somewhat wordy post, are two
things. First, path::begin() returns a mutable iterator. Shouldn't it be
returning a const iterator, for the same reasons as above? Same thing
goes for path::end().
Secondly, if it is really a good idea to return const objects for all
functions and not just operators, should that be a coding policy for
boost? Should we look over the other libraries and make sure they all
return const objects?
-- Mattias Flodin <flodin_at_[hidden]> - http://www.cs.umu.se/~flodin/ Room NADV 102 Department of Computing Science Umeå University S-901 87 Umeå, Sweden -- "If I have seen farther than others, it is because I was standing on the shoulders of giants." -- Isaac Newton "In the sciences, we are now uniquely privileged to sit side by side with the giants on whose shoulders we stand." -- Gerald Holton "If I have not seen as far as others, it is because giants were standing on my shoulders." -- Hal Abelson "In computer science, we stand on each other's feet." -- Brian K. Reid
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk