【问题标题】:Reference count for OVERLAPPED structureOVERLAPPED 结构的引用计数
【发布时间】:2014-03-19 14:33:53
【问题描述】:

我发现一篇我觉得很有趣的文章。只有一件事我无法理解。 (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&lt;OVERLAPPED&gt;* m_overlapped; 变量的作用是什么?我知道这会以某种方式计算引用,但我不确定它是如何在这里使用的,特别是因为构造函数没有通过OVERLAPPED 结构。这个类现在对ReadAsyncWriteAsync 方法中使用的OVERLAPPED 结构有何看法? 我尝试实现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;
};

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

【问题讨论】:

  • 我们看不到 OsAsyncFileOperation 构造函数,不需要让我们猜测它的样子。
  • 如果您的编译器中有 ReferenceCountedItem,我认为您可以使用 std::shared_ptr 替换它。

标签: c++ asynchronous overlapped-io


【解决方案1】:

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

【讨论】:

  • 我不太确定我明白你的意思。 OVERLAPPED 结构不会分配在ReadAsyncWriteAsync 内(因为会在那里调用带有 OVERLAPPED 结构的 ReadFile 和 WriteFile)? OsAsyncFileOperation 现在怎么可能是指针呢?
  • 您必须查看ReadAsync()WriteAsync() 的实现才能回答这个问题。我们在这里看不到这一点。要么他们使用了一些内部诡计将 OVERLAPPED 指针指向新的 OsAsyncFileOperation,要么文章没有准确反映代码的实际作用。
  • 好的。我也是这么想的。只是不确定我是否遗漏了什么。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多