Just highlight here, but
str = _str;
will not compile (you are trying to assign _str, which is the value of the string passed by reference, to str, which is the address of the string). If you want to do this, write:
str = &_str;
(and you will need to change either _str or str so that constnest matches).
But then, as your intuition told you, you would have leaked into the memory of which string object the string is already pointed to.
As stated earlier, when you add a variable to a C ++ class, you should think about whether this variable belongs to an object or something else.
If it belongs to an object, you will most likely be better off storing it as a value and copying the contents (but then you need to make sure that the copies are not running in your back).
It does not belong, then you can save it as a pointer, and you do not have to copy all the time.
Other people will explain it better than me, because I really can't handle it. What I end up doing a lot is writing code as follows:
class Foo { private : Bar & dep_bar_; Baz & dep_baz_; Bing * p_bing_; public: Foo(Bar & dep_bar, Baz & dep_baz) : dep_bar_(dep_bar), dep_baz_(dep_baz) { p_bing = new Bing(...); } ~Foo() { delete p_bing; }
That is, if an object depends on something in the sense of "Java" / "Ioc" (objects exist elsewhere, you do not create it, and you only want to call the method on it), I would save the dependency as a reference, using dep_xxxx.
If I create an object, I would use a pointer with the p_ prefix.
This is just to make the code more βimmediateβ. Not sure if this helps.
Just my 2c.
Good luck with mgt's memory, you're right that this is the hard part coming from Java; do not write code until you are comfortable, or you will spend hours chasing segaults.
Hope this helps!