【发布时间】: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<OVERLAPPED>* m_overlapped; 变量的作用是什么?我知道这会以某种方式计算引用,但我不确定它是如何在这里使用的,特别是因为构造函数没有通过OVERLAPPED 结构。这个类现在对ReadAsync 或WriteAsync 方法中使用的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