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

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!