A friend of mine is Learning C++ and he was given the assignment to create a String class that would implement constructor copy and '+' and '=' overloading without modifying the strings, i.e a = b means a and b both point to the same char*. The difficulty resides in making sure that doing c = b and then deleting a does not modify either b or c.
Apparently,a trick is to keep a pointer to the number of instances of string that point to the same string. But my friend gets unusual results at the end of his program so I thought perhaps somebody might be able to help a little more than I was.
Anyways, here's his implementation. + overloader isn't in there yet.
Make a struct Foo that has data in char* and a size_t counter. Make Newstring have one Foo*. Update counter when necessary. If counter hits 0, call delete.
Newstring is interface. Foo is hidden implementation. You can use pimpl idiom for extra fun.
Hmm, I don't think that's detailed enough. Besides, I think the code is almost correct, and doesn't need to be modified that much, and that it is more to the point of the assignement to stay true to its guidelines.
The string doesn't delete when the destructor is called, which is good, however the nbref variable behaves strangely. Sorry, probably should have been clearer about this.
Edit : I see what you mean, but is it really necessary to have such a struct ?