What happens with
pass_by_const(const std::string& s)
{
pass_by_non_const(s);
}
is: pass_by_const
has const argument std::string s
, so it is not allowed to modify the string s defined in enclosing scope and passed to him as an argument. However, pass_by_non_const
is allowed to modify s. This raises compiler error at compile time.
A local non-const copy of s can be passed to pass_by_non_const
however. Then, the local copy may be modified in the scope of pass_by_non_const
, whereas the enclosing scope's s passed as an argument to pass_by_const
is not altered.
Right way to write the method is then
pass_by_const(const std::string& s)
{
std::string local_copy = s;
pass_by_non_const(local_copy );
}
No more compile time error, local_copy may be modified in most inner scope, whereas s from enclosing scope won't be, which abide by the pass-by-const-ref-ness of the pass_by_const
method.