QByteArray data("Hello, world!"); QByteArray copy = data; // creates a shallow copy of data data[0] = 'h'; // modifies data qDebug() << data; // outputs "hello, world!" qDebug() << copy; // outputs "hello, world!"
QByteArray data("Hello, world!"); QByteArray copy = data; // creates a shallow copy of data QByteArray deepCopy = copy.detach(); // creates a deep copy of copy copy[0] = 'h'; // modifies copy deepCopy[0] = 'H'; // modifies deepCopy qDebug() << data; // outputs "Hello, world!" qDebug() << copy; // outputs "hello, world!" qDebug() << deepCopy; // outputs "Hello, world!"In this example, we create a deep copy of the copy variable using the detach function, and then modify both the copy and deepCopy variables. Since deepCopy was detached from the shared data, it is not affected by the modifications to copy, while the original data variable is not affected by any of the modifications. The package library for QByteArray and its detach function is the Qt library.