This is guaranteed to work with significant reservations.
All reservations come down to two main issues, which are combined in such a way that it is not very pleasant:
- In your complete program, there is only one instance of
String . String not a constant.
This will cause you all sorts of interesting problems. For example, if you call __str__ again to another place in your program, anyone who saved a copy of the const char * that you passed back may end up with an invalid pointer. And even if it is not, they will return a pointer to the memory that has changed. In short, the result will be undefined behavior.
Another example: if you call __str__ from more than one thread, it will explode at some point, since both threads are trying to change String at the same time.
Fortunately, you do not have a static initialization task. String guaranteed to be initialized the first time __str__ called.
You can solve the String problem by staying forever by calling String.clear() in __str__ if you are sure that no one has a const char * indicating the status of your String . String.clear() free up any storage that it can use.
Personally, I would use this only as a last resort. The possibility of random parts of the program throwing a pointer could endlessly bother me. There is no clear indicator of the lifetime of this pointer, except that it cannot be guaranteed that it will work if __str__ ever called again. But then again, it may be, depending on what exactly __str__ does.
In addition, __str__ is a bad name to use. Names containing two consecutive underscores are reserved for implementation in C ++.
source share