Is this the correct behavior to return a const char * vector populated inside a function

I am currently studying volcanoes. In one of the lessons, I saw a function that roughly does the following:

#define SOMESTRING "Hello World!"

std::vector<const char*> buildVector() {
    std::vector<const char*> vec;
    vec.push_back(SOMESTRING);
    return vec;
}

When I saw this, I was wondering: is this a specific behavior? Isn't the contents of the string "Hello World!"on the stack and therefore invalid after the function returns? If this behavior is undefined, what would be the correct way to do this? Unfortunately, use is std::stringnot an option due to the volcano API.

+4
source share
1 answer

, SOMESTRING , .. . .

:

  • #define SOMESTRING "Hello World!"
    -- . , , .
  • const char* SOMESTRING = "Hello World!"
    -- . , .
  • char SOMESTRING[] = "Hello World!";
    - , .
    - BAD, .
  • char* SOMESTRING = new char[X]; strncpy(SOMESTRING, "Hello World!", N);
    - , (.. ) , . , vector, , .

BTW, std::vector / . c-, .

+2

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


All Articles