OVERLAPPED结构的引用计数

时间:2014-03-19 14:33:53

标签: c++ asynchronous overlapped-io

我发现了一篇我觉得非常有趣的文章。只有一件事我无法绕过头脑。 (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结构。现在,该课程如何处理OVERLAPPEDReadAsync方法中使用的WriteAsync结构? 我试图实现ReferenceCountedItem类,因为它没有在文章中指定:

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

我大多不确定这一切是如何粘在一起的。也许有人可以解释一下它。如果您需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

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