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

标签 c++ dynamic-memory-allocation

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

函数如下:

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

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

    return arr;
}

这是一个使用示例:

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

    green = test.getColor()[1];
}

因为它不是对象,所以我无法删除 RGB 类析构函数中的任何内容。 我怎样才能确保内存在“getColor()”函数使用结束时被删除? 谢谢。

最佳答案

我想这可以为您省去一些麻烦:

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
}

试图实现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!
}

实际上,如果:

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

关于c++ - 如何释放在 "get"函数中分配的动态内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25623447/

相关文章:

c++ - cpp 文件 #include 导致错误,@class 不

C++分配动态结构

c++ - window.display() 单独在最后显示的和当前显示的缓冲区之间切换

c++ - strdup 后如何释放内存?

c++ - 通过引用数组传递堆栈分配的参数

c++ - 段错误 - 将变量传递给方法会更改全局值

C 动态内存分配 - 从文件读取数据

c - 动态分配数组,无需 malloc 和 calloc

c++ - std::function 和 shared_ptr

linux - 汇编 x86 brk() 调用使用