如何创建动态分配的const对象数组,但要为其赋值

How to create a dynamically-allocated array of const objects, but have values assigned to them?

本文关键字:数组 赋值 对象 const 何创建 创建 动态分配      更新时间:2023-10-16

我需要创建一个动态分配的const对象数组。困难的是,我还需要给const对象赋值。

我需要这个SFML类的Samples变量

我该怎么做?

您不需要const对象的数组。指向const的指针既可以指向const对象,也可以指向非const对象;你可以创建一个动态数组,并从它初始化一个Chunk结构,像这样:

std::vector<Int16> samples;
initialise(samples);
// valid until 'samples' is destroyed or resized
SoundStream::Chunk chunk = {&samples[0], samples.size()};

Easy:

// Step 1: Make an array of const values:
const int arr[] = { 1, 4, 9, 17 };
// Step 2: Make a pointer to it:
auto        parr     = &arr; // 2011-style
const int (*pbrr)[4] = &arr; // old-style

你不能给常量"赋值"(显然),所以给常量赋值的唯一方法是初始化为该值。

或者,如果在编译时不知道数据:

const std::vector<int> function() {
    std::vector<int> tmp(5); //make the array
    for(int i=0; i<5; ++i)
        tmp [i] = i; //fill the array
    return tmp;
}

进行分配,将其赋值给指向非const的指针。对数据进行修改。当你做了这些乱七八糟的事情之后,你可以把const指针赋值给数组。例如:

int * p = new int[100];
for (int i=0; i<100; ++i)
    p[i] = i;
const int * cp = p;

如果需要动态分配数组,我建议使用标准容器:

std::vector<Int16> data;
Chunk* c = ...;
data.push_back(...);
c->Samples = &data[0];