Decorate char * and char const * by getting a pointer: good practice?

Hello, I wanted to ask the public about my idea of ​​creating a string class (for example, std::string ) that could be able to work with buffers provided by the client.

What dangers do you see? is it a classic smell? etcaetera

I mean this:

 char ext[64] = {0}; my::string s(ext, my::string::acquire_RW); size_t len = s.size(); size_t pos = s.find("zboub"); my::string s2(s); // uses true (alloc+)copy semantic here. 

So, I foresee 2 strategies: acquire_RW and acquire_RO , which would allow to change characters in ext or not. And in the case of RO for any non-constant method and RW cases in methods where the buffer should be expanded; he will transfer and copy only at that moment.

In some ways, the type my::string becomes a decorator of type char* .

Of course, be careful not to free the external buffer before the decorator remains as a client requirement.

Thanks for sharing your concerns.

+4
source share
2 answers

The answer to “good practice” is difficult. I would say, in general, not a good practice, but for some specific use cases it is a very good practice. It all depends on how well you can trust the client throughout the life of the provided memory. In general: no trust. In special cases: OK.

There is one pretty important thing to consider performance:

Do you plan to use an implicit exchange (with a copy for recording and counting links) of your selected variants of your lines? Or do you plan to use the semantics of values ​​(always copy, not reference)?

In multiprocessor and multithreaded environments, semantics are the preferred way for strings. Increased productivity through the use of implicit sharing is destroyed by the necessary blocking in multi-threaded environments.

Please note that your sentence may make sense even with multithreading: you can use copy-on-write perfectly when moving from your external memory to the selected option (without the need for locking) and the semantics of values ​​from now on (also no locking is necessary). That would be better.

I would suggest that your option works well in very specific use cases, for example, when you copied memory to some file with a lot of lines, and you do not want to store copies of these small lines and fragment memory.

However, in the general case, I would not bother and just use std::string .

+1
source

I think this is a great idea, but I will stick to reading only; std::string great for RW unless, of course, there is a situation where you can save some memory allocation.

This is quite an optimization, so maybe it’s not worth the effort if you don’t know that your static lines are causing problems.

0
source

All Articles