I have a member function like
setResult(const std::string &s)
{
this->m_result =开发者_开发知识库 s;
}
After checking, I found this->m_result
's address is the same as s
. Will m_result
disappear (or become garbage) when s
goes out of scope if s
is a stack object?
Probably not; if m_result
is a std::string, it will deep-copy the data contents.
Anyway, in places like assignment operators, you'd normally check against this kind of self-assignment. The idiom is:
obj& operator=(const obj& o) {
if ( this != &o ) // ...
}
The same goes for your case, where you could potentially check it &m_result
is different from the passed in string. But std::string are usually implemented so that self-copying is OK.
Effectively s
is no stack object, as it's a reference (the reference itself is a stack object, but the string is not). Actually this->m_result
can only have the same address as s, if you passed this->m_result
to testResult
, but although self-assignment is quite useless, in this case it doesn't do any harm.
EDIT: Another case could be, that this->m_result
is not a std::string but a reference to it. Then you got a problem as you got a reference to a destroyed object. Remember, a reference is nothing more than a pointer (just more comfortable to use and with reduced functionalty).
精彩评论