如何释放我在"get"函数中分配的动态内存?

arg*_*nza 2 c++ dynamic-memory-allocation

我正在创建一个函数,它将返回一个我必须为其分配内存的数组,但是我找不到一种方法来确保在程序结束时删除内存.

这是功能:

int* RGB::getColor() const{
    int* arr = new int[3];

    arr[0] = red;
    arr[1] = green;
    arr[2] = blue;

    return arr;
}
Run Code Online (Sandbox Code Playgroud)

这是一个使用它的例子:

int main(){
    int green;
    RGB test(50, 100, 150);

    green = test.getColor()[1];
}
Run Code Online (Sandbox Code Playgroud)

由于它不是一个对象,我无法删除RGB的类析构函数中的任何内容.如何确保在"getColor()"函数结束时删除内存?谢谢.

Mar*_*Mao 5

我想这可以为你节省一些麻烦:

class RGB
{
public:
    RGB(int r, int g, int b)
    {
        colors[0] = r;
        colors[1] = g;
        colors[2] = b;
    }

    int operator[](uint index)
    {
        // you can check index is not exceeding 2, if you want
        return colors[index];
    }

    int getColor(uint index)
    {
        // you can check index is not exceeding 2, if you want
        return colors[index];
    }

private:
    int colors[3];
};

int main(){

    RGB test(50, 100, 150);
    int green = test[1];
    // int green = test.getColor(1); // or you really want to use it this way
}
Run Code Online (Sandbox Code Playgroud)

试图在评论中实现OP请求的修改版本:

struct Color
{
    int values[3];

    int operator[](uint index) const
    {
        // you can check index is not exceeding 2, if you want
        return values[index];
    }
};

class RGB
{
public:
    RGB(int r, int g, int b)
    {
        color.values[0] = r;
        color.values[1] = g;
        color.values[2] = b;
    }

    Color getColor() const
    {
        return color;
    }

private:
    Color color;
};

int main() {
    RGB test(50, 100, 150);
    int green = test.getColor()[1]; // no need to worry about memory management!
}
Run Code Online (Sandbox Code Playgroud)

实际上,如果:

struct Color
{
    int r;
    int g;
    int b;

    enum Type
    {
        RED = 0,
        GREEN = 1,
        BLUE = 2,
    };

    int operator[](Type type) const
    {
        return values[type];
    }
};

class RGB
{
public:
    RGB(int r, int g, int b)
    {
        color.r = r;
        color.g = g;
        color.b = b;
    }

    Color getColor() const
    {
        return color;
    }

private:
    Color color;
};

int main() {
    RGB test(50, 100, 150);
    int green = test.getColor()[Color::GREEN];
}
Run Code Online (Sandbox Code Playgroud)