What is the best pattern for returning a dynamically allocated buffer from a function in C ++?

I am reorganizing the old code. There is a C style function that works as follows: (Obviously, I have simplified this here)

int LoadData(char** buf1, int* buf1Len, char** buf2, int* buf2Len) {
    *buf1Len = DetermineLength1();
    *buf1 = (char*)malloc(*buf1Len);
    // Fill buf1
    *buf2Len = DetermineLength2();
    *buf2 = (char*)malloc(*buf2Len);
    // Fill buf2
    int result = 0; // Or some other INT depending of result
    return result;
}

Now, I would like to update this code to somehow return a unique_ptr or equivalent, so the pointer will be automatically controlled by the caller and the caller will never forget to free up memory.

I did not find a good solution, so currently I have changed the code to the following:

int LoadData(std::unique_ptr<char[]>* ubuf1, int* buf1Len, std::unique_ptr<char[]>* ubuf2, int* buf2Len) {
    // same code as above, and finally:
    ubuf1->reset(buf1);
    ubuf2->reset(buf2);
    return result;
}

This does not look good, so I am looking to see if there is a better solution. Since I am returning two buffers, use unique_ptras the return value is not an option.

Is there a better way to do this?

+4
1

std::unique_ptr , . std::vector. , . char* , std::string.

std::pair<std::vector<char>, std::vector<char>>
LoadData()
{
    std::vector<char> buf1(DetermineLength1());
    // Fill buf1

    std::vector<char> buf2(DetermineLength2());
    // Fill buf2

    return { std::move(buf1), std::move(buf2) };
}

int, std::tuple<int, std::vector<char>, std::vector<char>>. .

+10

Source: https://habr.com/ru/post/1676597/


All Articles