I want to do the following:
std::unique_ptr buffer = new char[ /* ... */ ] { \"/tmp/file-XXXXXX\" };
Obviously, it doesn\'t work
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.
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.
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.