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

后端 未结 3 1245
心在旅途
心在旅途 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<char, sizeof("/tmp/file-XXXXXX")> arr{ "/tmp/file-XXXXXX" };
    

    You can reduce the boilerplate using a macro:

    #define DECLARE_LITERAL_ARRAY(name, str) std::array<char, sizeof(str)> 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.

    0 讨论(0)
  • 2021-01-21 17:49

    I don't get why you're not using std::string; you can do str.empty() ? NULL : &str[0] to get a non-const pointer, so the constness of str.c_str() is not going to pose a problem.

    However, note that this is not null-terminated.

    0 讨论(0)
  • 2021-01-21 18:00

    Since you requested a dynamic array and not wanting to count the length, that rules out std::array<char,N>. What you're asking for is really just std::string - it's dynamic (if need be), and initializes just fine from a char* without counting the length. Internally, it stores the string in a flat array, so you can use it as such, via the c_str() call.

    0 讨论(0)
提交回复
热议问题