Main Content

Copy C++ MATLAB Data Arrays

The matlab::data::Array class supports both copy and move semantics. Copies of Array objects create shared data copies. In the following C++ code, variables B and C are copies of matlab::data::CharArray A; all three variables point to the same data.

#include "MatlabDataArray.hpp"

int main() {
    using namespace matlab::data;
    ArrayFactory factory;
    CharArray A = factory.createCharArray("This is a char array.");

    // Create a shared copy of A
    CharArray B(A);

    CharArray C = factory.createCharArray("");
    // Copy the contents of A into C
    C = A;

    return 0;
}

Array supports copy-on-write semantics. Copies of an Array object are unshared when a write operation is performed. In the previous example, modifying the variable B creates a copy of the CharArray object with updated data. However, A and C remain shared copies.

   // B becomes unshared once modified
    B[20] = char16_t(33);

C++ MATLAB® Data Arrays support move semantics. When you pass a variable using move, there is no copy of the variable.

Avoid Unnecessary Data Copying

If you index into or use an iterator on an array for read-only purposes, then the best practice is to declare the array as const. Otherwise, the API functions might create a copy of the array in anticipation of a possible copy-on-write operation.

See Also