问题
So when new
ing an array of char
s I can value initialize:
const char* foo = new char[4]{'J', 'o', 'n', '\0'};
What I want to know is how to use a variable in that initializer_list
:
const string initializer{"jon"};
const char* foo = new char[4]{initializer.c_str()}; // This doesn't work, can I make it work?
回答1:
You can use a variable, but you can't use a string and expect the compiler to magically split it up.
const char* ip = initializer.c_str();
const char* foo = new char[4]{ip[0], ip[1], ip[2], ip[3]};
Once you have a variable length, though, this doesn't work at all. You just have to allocate and then use string::copy
to fill the array in a separate step.
来源:https://stackoverflow.com/questions/27504692/how-do-i-use-a-variable-in-news-value-initialization