如何在新的[]的值初始化中使用变量 [英] How Do I Use a Variable in new[]'s Value Initialization

查看:130
本文介绍了如何在新的[]的值初始化中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以当 new 数组 char 时,我可以初始化值:

So when newing an array of chars I can value initialize:

const char* foo = new char[4]{'J', 'o', 'n', '\0'};

我想知道的是如何使用 initializer_list

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?


推荐答案

可以使用变量,使用一个字符串,期望编译器将其分裂。

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]};

一旦你有一个可变长度,但是,这根本不工作。你只需要分配,然后使用 string :: copy 在单独的步骤中填充数组。

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.

这篇关于如何在新的[]的值初始化中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆