Say we have a function store
void store(const QByteArray& data);
This function's job is to take data and store it away. Unfortunately, it is not safe to do that if the argument was created with QByteArray::fromRawData(ptr, size), because it and all its copies require that ptr remains valid.
Therefore store has no option to forbid its callers to pass in such an array, to treat data as if it was a const char* on stereoids or to force a deep-copy with detach. All of this is not satisfying and especially the latter hurts performance because if data was COW-copied before being passed to store, we will be doing an unnecessary deep-copy.
QByteArray has a private function nulTerminated whose implementation seems to do just what I want: If it doesn't own the memory, it deep copies. And if it owns the memory, it does nothing but return *this.
Two questions really
Is there a work-around using
publicfacilities?The Qt docs mention that
ptrmust only be alive for the lifetime of the return value and any copies of it. If you say.right(.size()), it would seem this is not a copy, so Qt would need to make a deep copy according to the docs. But does it really do so?