How to initialize the dynamic array of chars with

2020-04-14 09:55发布

问题:

I want to do the following:

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

Obviously, it doesn't work because I haven't specified the size of a new array. What is an appropriate way to achieve my goal without counting symbols in a string literal?

Usage of std::array is also welcome.

Update #1: even if I put the size of array, it won't work either.

Update #2: it's vital to have a non-const access to the array as a simple char* pointer.

回答1:

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.



回答2:

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.



回答3:

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.