-1

我来自python世界,内存管理得到了照顾。最近开始编写一些严肃的 C++ 代码,我对内存分配实践很好奇。我知道 K&R 建议使用void函数来进行任何类型的大数组操作。虽然这是完成工作的一种完全有效的方式,但我更喜欢我的函数返回更具描述性。

因此,另一种解决方案是让类似的东西int * function (int param) {}返回一个已malloc在函数中编辑的内存块。但不能保证free以后谁会使用该功能。

那么问题来了:“是否有标准的方法来记录内存分配函数?”。在某种程度上,我想强迫 API 用户free阅读文档,因为我真诚地相信他们会阅读文档。

也许还有其他一些方法可以强制执行简单的引用计数free

在采取任何答案之前,我正在寻找STL答案,因为我们希望尽可能避免Boost

谢谢大家。

4

5 回答 5

2

如果您需要从函数返回一个动态大小的数组(正如您问题中的文本所表明的那样),那么正确的解决方案是向量。

std::vector<int> function(int param)
{
    std::vector<int> v;
    ...
    return v;
}

没有理由在这里涉及指针,无论是智能的还是其他的。

于 2013-11-06T23:19:20.170 回答
2

我建议看看一些 STL 指针类,特别是std::auto_ptr(见下面的评论)和std::unique_ptr.

于 2013-11-06T22:48:27.463 回答
1

A great deal here (almost everything, to be honest) depends on what you're really planning to do.

A few things are pretty easy though. First, you should almost never use malloc or free in C++. While there may be a few situations in which it's (arguably) reasonable to do so, they're unusual, and probably not something you should even consider until you really know what you're doing (at which time, you'll probably reject them, regardless of my advice). Likewise, you should avoid using raw pointers. Again, you might eventually encounter a situation where they're the best tool available, but for now (and the next year or two, at least) it's probably best to nearly forget that they exist at all.

Smart pointers are kind of a half-way point. While certainly a lot more acceptable than a raw pointer, they're still (at least in my opinion) less than desirable. Personally, I almost never use them either, though there are some pretty good C++ coders who use them a lot more than I do.

Some have already advised that you should typically work with something like an std::vector instead of using a pointer at all -- and I'd agree that this is good advice. I'd advise that you at least consider going a step further still: to the extent that it's at all reasonable, you should write your code as generic algorithms that work with iterators instead of working directly with a container.

For a simple example, let's consider an array of numbers, of which we want to find the arithmetic mean. Using raw memory, this might look something like:

double mean(double *data, size_t size) { 
   double total = 0.0;

   for (int i=0; i<size; i++)
      total += data[i];
   return total / size;
}

As pointer usage goes, that's fairly innocuous, but they're right that it can be cleaner if we use an std::vector:

double mean(std::vector const &v) { 
    double total = 0.0;

    for (int i=0; i<v.size(); i++)
       total += v[i];
    return total / v.size();
}

Using iterators with an algorithm for the standard library, we can simplify that a bit though:

template <class Iter>
double mean(Iter b, Iter e) {
    return std::accumulate(b, e, 0.0) / std::distance(b, e);
}

With this, we're no longer tied to one particular container type. For example, if we happen to have the numbers stored in a std::deque or std::list instead of a std::vector, this will still work just fine:

std::deque<double> numbers { 1.2, 3.4, 5.6, 7.8};

double average = mean(numbers.begin(), numbers.end());

std::list<double> more_numbers { 1.414, 1.732, 2.0 };

double another_average = mean(more_numbers.begin(), more_numbers.end());

This can also work for situations where we're producing multiple results, for which we need to allocate space. For example, if we took one collection of data as input, and produced another collection of data as output, we might call something like:

std::vector<something> results;

std::my_algorithm(input.begin(), input.end(), std::back_inserter(results));

In this case, the back_inserter returns an instance of a std::back_insert_iterator<T>, which will use the vector's push_back to insert results when we write to the iterator.

于 2013-11-06T23:25:38.333 回答
1

现代 C++ 提供了几个所谓的智能指针类来帮助进行内存管理。通常不需要使用malloc/free甚至new/ delete。自 C++11 起标准化的最重要的智能指针类是:

要生成智能指针拥有的对象,您应该了解:


聪明的!

于 2013-11-06T23:03:51.330 回答
-1

我建议使用引用来声明您的函数,例如作为参数的向量,以确保向量存在并由调用者分配。因此调用者将负责对象的生命周期,您只需将其填充到被调用者中。

http://www.informit.com/articles/article.aspx?p=373338&seqNum=2

于 2013-11-06T22:50:02.400 回答