gpt4 book ai didi

c++ - C/C++ 通过调用引用或直接释放指针

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:24 25 4
gpt4 key购买 nike

struct State {
int* maxLiters;
int* nowLiters;
} parentState;

void makeState(State& s) {
if ((s.maxLiters = (int*)malloc(cups*sizeof(int))) == nullptr) {
error();
}
if ((s.nowLiters = (int*)malloc(cups*sizeof(int))) == nullptr) {
error();
}
}

void delState(State& s) { // or delState(State s) ?
free(s.maxLiters);
free(s.nowLiters);
}

我一直在用 C 编写代码,并且真正开始使用 C++。我很抱歉使用“malloc”。

在“delState”函数中,我通过引用传递了结构。我有点不确定是否也可以像评论中那样按值传递它。在 C 中,我通常会使用指针来执行此操作,以便在调用创建和删除函数时始终放置一个“&”。由于使用引用参数我不应该键入“&”,所以我很想创建一个纯按值调用函数。考虑一下我自己确实说“好的”,因为无论哪种方式,通过引用或通过值,“免费”函数将获得相同的内存地址。但我只是担心,因为我从未这样做过。

任何澄清都会有所帮助,在此先感谢。

最佳答案

如果您想使用 C++,最好学习“C++ 方式”做事。在这种情况下,您不应该真正调用函数来为您创建和删除状态,而应该使用类构造函数和析构函数。此外,通常最好使用 std::vector 而不是使用数组。对于您的示例,这看起来像:

class State {
public:
State (size_t cups)
: maxLiters(cups), nowLiters(cups) //reserve "cups" amount of space in the vectors
{ }

~State () =default; //default destructor, will call the vector destructors and delete the data automatically
State (const State &other) =default //default copy constructor, will copy the contents of the vectors into a new State object
State &operator= (const State &other) =default //default assignment operator, will overwrite the contents of this object with the new one

std::vector<int> maxLiters;
std::vector<int> nowLiters;
};

然后如果你想处理内存不足的错误,你可以在创建状态对象时这样做:

try
{
State s(12);
...
}
catch (std::bad_alloc &ba)
{
error();
}

但是,捕获 bad_alloc 异常通常没有意义,因为从类似的事情中恢复从困难到不可能,尤其是在抛出异常时某些数据结构已损坏的情况下。

现在您的类管理堆分配的数据,您应该考虑复制和分配此类的对象并定义复制构造函数和赋值运算符重载(如果默认值不适合您)意味着什么。这被称为 Rule of Three .

您还应该考虑通过将 vector 声明为私有(private)并为其提供 getter/setter 来封装 vector 。即使为了接口(interface)一致性而同时声明 getter 和 setter,这也是一种很好的做法。

关于c++ - C/C++ 通过调用引用或直接释放指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com