std::string reverse(const std::string& s)
VS is complaining that you are trying to create a non-const object reference from a const object.
If something starts a const
, you cannot use non-const iterators over it -- because the point of the const-ness is that you are guaranteeing that the object cannot be changed. If you can suddenly treat it as non-const, where does the guarantee go?
In this specific case, your problem is a little more involved than at first blush.
class takes as a non-explicit constructor a const char*
(a "c-string") -- which means that a thing like
can be automatically converted into a std::string
where one is expected.
That is done, leaving you with a temporary string somewhere. In this case, that means that the temporary string is const
-- you cannot change it. (This is a language characteristic -- the idea is that there is no point in modifying the string since it will have no effect -- the temporary is destroyed after the function terminates -- and modifications can have side-effects that adversely affect the compiler's ability to reason about your program.)
However, the function takes a reference to a modifiable
(non-const) string. (The technical term is mutable
.) Meaning that automatically-created objects are not usable as arguments to the function.
Since you don't change the argument string anyway, just make it a const reference
to a string -- and suddenly everything matches up (const is const) and everything is happy.
Hope this helps.