Why return string& from a const method won't compile?
Given the following code:
#include <iostream>
#include <string>
using namespace std;
class A
{
private:
string m_name;
string m_first;
public:
A(): m_first("string") {}
virtual void print() const {}
string& getName() const {return m_first;} // won't compile
const string& getLastName() const {return m_name;} // compile
};
int main()
{
A a;
return 0;
}
Compiler presents : "invalid initialization of reference of type 'std::string&' from expression of type 'const std::string'"
Why can't I return "m_first" fr开发者_运维技巧om getName() ? I thought that the const on the tail of the function states that the function will not change 'this'... but I'm not trying to change this , just return a data member.
Because inside a const method, all non-mutable
members are implicitly const
. So, you're trying to bind a reference to non-const std::string
(your return value) to an object of type const std::string
, which is illegal(because it would allow modification of const data), hence the error.
By returning a reference, you are saying you can modify the class data-member that the reference-variable is implicitly pointing to, and therefore modify the class ... but you have dedicated the class method as a constant method, meaning it is not allowed to change any class member variables that have not been specifically declared mutable. So by returning a non-constant reference, you are breaking the encapsulation "contract" that the class interface has established. Your options are to either return a temporary object (i.e., that creates a copy of the object), or a constant-reference. So you could either do
const string& getName() const {return m_first;}
or
string getName() const { return m_first; } //copies m_first and returns the copy
Your code promises that the reference won't change the m_name member, but you return a reference that can change it. What you want is a string const& return type.
This returns a "read-only" reference to m_name.
See also: the C++ FAQ on const correctness
When you return string &
, it allows modifying class member... but the function is const
, so it is not allowed to allow such a situation. But when you return const string &
, it doesn't allow modifying class instance.
What if you call A.getName().ModifyTheString()
==> this means you modified this
.
精彩评论