【发布时间】:2014-03-10 17:33:22
【问题描述】:
考虑一个MemoryMappedFile 类,它具有以下数据成员:
class MemoryMappedFile
{
....
private:
// RAII wrapper to some OS-specific raw handle (e.g. Win32 HANDLE),
// representing the memory-mapped file.
Handle m_handle;
// Pointer to file begin (first file byte).
BYTE* m_first;
// Pointer to file end (one byte past last file byte).
BYTE* m_last;
};
Handle 类是某些特定操作系统原始类 C 句柄的 RAII 包装器(例如,考虑 Win32 HANDLE)。它不可复制,但它是可移动的。
相反,m_first 和 m_last 是映射到文件内容的内存区域内的原始指针。
我希望MemoryMappedFile 类可移动(但不可复制,就像Handle 类一样)。
如果不是原始指针,根据 C++11 的规则自动通过成员移动生成移动构造函数,该类将自动 可移动的。
不幸的是,原始指针迫使我编写自定义移动构造函数:
MemoryMappedFile::MemoryMappedFile(MemoryMappedFile&& other)
: m_handle( std::move(other.m_handle) )
{
// Move m_first
m_first = other.m_first;
other.m_first = nullptr;
// Move m_last
m_last = other.m_last;
other.m_last = nullptr;
}
如果 C++ 标准库有某种形式的“笨拙但可移动”的指针就好了,它的开销为零,就像原始指针一样(观察 em> 非拥有指针),但定义了移动操作(移动构造函数和移动赋值),以便编译器可以在将这些指针作为数据成员的类中自动生成正确的移动操作。
在 C++ 标准库或 Boost 中是否有类似的东西?
或者有没有其他方法可以实现相同的目标(除了编写我自己的自定义 ObservingPointer 类、包装原始指针和定义移动操作)?
【问题讨论】:
-
std::unique_ptr怎么样?它是零开销、不可复制、可移动的,如果您不想在销毁时使用 auto-delete,您可以给它一个自定义删除器。