First of all, your A::s_ is a reference to std::string ; this means that he refers to something that must exist somewhere.
Due to its reference type and the fact that links must be initialized at the time of their creation, you must initialize A::s_ in all A constructors (as indicated by other users):
class A { public: A(string& s) : s_(s) { cout << "A::ctor" << endl; } A(const A& rhs) : s_(rhs.s_)
And now, to the first that I mentioned; A::s_ should refer to something existing, so you should know about some things, look at the following code:
int main() {
Creating this instance of A , we provide the value const char[12] , with this value a temporary std::string and assigned to the constructor A::A(string& s) . Where is A::s_ referenced after the constructor completes? What happens to the created temporary std::string ? Is this lifetime extended or does it just die when constructor A ends? Are you sure you need a link?
std::string s("hello world"); int main() {
Using the above code, a new instance of A , calling the same constructor A::A(string& s) , but with the provided string lying in the global scope, so it is not destroyed and the A::s_ from A instance refers to a valid string for life, but the real threat lies in the copy constructor:
std::string s("hello world"); int main() { A a(s);
The copied value of the object will refer to the std::string this object! Is this what you want?
source share