How to initialize the dynamic array of chars with a string literal in C++?

后端 未结 3 1275
心在旅途
心在旅途 2021-01-21 17:24

I want to do the following:

std::unique_ptr buffer = new char[ /* ... */ ] { \"/tmp/file-XXXXXX\" };

Obviously, it doesn\'t work

3条回答
  •  死守一世寂寞
    2021-01-21 17:43

    Here's a solution based on std::array:

    std::array arr{ "/tmp/file-XXXXXX" };
    

    You can reduce the boilerplate using a macro:

    #define DECLARE_LITERAL_ARRAY(name, str) std::array name{ str }
    DECLARE_LITERAL_ARRAY(arr, "/tmp/file-XXXXXX");
    

    The sizeof is evaluated at compile-time, so there is no runtime scanning of the literal string to find its length. The resulting array is null-terminated, which you probably want anyway.

提交回复
热议问题