Warm tip: This article is reproduced from serverfault.com, please click

Conversion of const char** to std::vector<const char *>

发布于 2020-12-09 15:53:02

I am currently working on a Vulkan project that uses the glfw library for window handling.

To get the required extensions glfw provides const char** glfwGetRequiredInstanceExtensions(uint32_t *count).

To avoid passing around a const char** together with the count i wrote a simple helper function that converts the const char** to a std::vector<const char *>:

std::vector<const char *> GetRequiredInstanceExtensions()
{
    uint32_t extensionCount = 0;
    auto extensions = glfwGetRequiredInstanceExtensions(&extensionCount);

    return std::vector<const char *>(extensions, extensions + extensionCount);
}

I am not sure how this works memory wise. From what i understand the data gets copied into the vector here. I am not sure if i have to clean up the const** that gets returned from glfwGetRequiredInstanceExtensions and if it's fine to use a std::vector<const char *> in general. The vector is just cleaning up the pointers and not the whole c-strings when it goes out of scope if i am not mistaken.

Do i have memory leaks here?

Questioner
Eric
Viewed
0
scohe001 2020-12-09 23:57:32

From the Vulkan docs on glfwGetRequiredInstanceExtensions():

Pointer lifetime

The returned array is allocated and freed by GLFW. You should not free it yourself. It is guaranteed to be valid only until the library is terminated.

So you don't need to worry about the memory at all. std::vector will clean up after itself and Vulkan will as well.