0

我发现了一篇我觉得很有趣的文章。只有一件事我无法理解。( http://molecularmusings.wordpress.com/2011/08/31/file-system-part-1-platform-specific-api-design/ ) 作者描述了一个能够处理同步和异步文件操作的 File 类. 对于异步操作,他使用了一个自包含对象,该对象在内部跟踪异步操作。该类如下所示:

class OsAsyncFileOperation
{
public:
  OsAsyncFileOperation(HANDLE file, size_t position);
  OsAsyncFileOperation(const OsAsyncFileOperation& other);
  OsAsyncFileOperation& operator=(const OsAsyncFileOperation& other);
  ~OsAsyncFileOperation(void);

  /// Returns whether or not the asynchronous operation has finished
  bool HasFinished(void) const;

  /// Waits until the asynchronous operation has finished. Returns the number of transferred bytes.
  size_t WaitUntilFinished(void) const;

  /// Cancels the asynchronous operation
  void Cancel(void);

private:
  HANDLE m_file;
  ReferenceCountedItem<OVERLAPPED>* m_overlapped;
};

并且是这样使用的:

OsAsyncFileOperation ReadAsync(void* buffer, size_t length, size_t position);

现在我想知道:ReferenceCountedItem<OVERLAPPED>* m_overlapped;变量的作用是什么?我知道这会以某种方式计算引用,但我不确定它是如何在这里使用的,特别是因为构造函数没有通过OVERLAPPED结构。这个类现在如何了解or方法OVERLAPPED中使用的结构?我试图实现这个类,因为它没有在文章中指定:ReadAsyncWriteAsyncReferenceCountedItem

#pragma once

template <typename T>
class ReferenceCountedItem {

public:
    ReferenceCountedItem(T* data) :m_data(data), m_refCounter(1)
    {}

    ~ReferenceCountedItem() {}

    int addReference()
    {
        return ++this->m_refCounter;
    }

    int removeReference()
    {
        return --this->m_refCounter;
    }

private:
    T* m_data;
    int m_refCounter;
};

我主要不确定这一切是如何结合在一起的。也许有人可以对此进行更多解释。如果您需要更多信息,请告诉我。

4

1 回答 1

0

new作者在某处使用or分配堆上的 OVERLAPPED 结构GlobalAlloc。然后,在复制构造函数中operator=,他正在复制指针。由于可以有多个对象使用该指针,因此他使用引用计数来知道何时可以删除 OVERLAPPED 指针。

于 2014-03-19T14:50:38.100 回答