當類具有mmap地址指針時,是否可以使用複製構造函數?我在想,mmap只被調用過一次,所以只有一個引用已經在內核中註冊了。現在兩個對象共享該地址,當刪除1時,該地址會發生什麼?我想這是清理。如果可能的話,mmap文件會爲我處理同步嗎?使用mmap地址複製構造函數
0
A
回答
2
shared_ptr
是你的朋友在這裏:
#include <sys/mman.h>
#include <memory>
std::shared_ptr<void> map_some_memory(void *addr, size_t length,
int prot, int flags,
int fd, off_t offset)
{
auto deleter = [length](void* p) {
munmap(p, length);
};
// use of a custom deleter ensures that the mmap call is undone
// when the last reference to the memory goes away.
return { mmap(addr, length, prot, flags, fd, offset), deleter };
}
// some function that gets you a file descriptor
extern int alloc_fd();
int main()
{
int some_file = alloc_fd();
// allocate a shared mapping
auto my_mapped_ptr = map_some_memory(nullptr, 100, PROT_READ | PROT_WRITE,
MAP_SHARED, some_file, 0);
// cast it to sometthing else
auto shared_ints = std::shared_ptr<int>(my_mapped_ptr,
reinterpret_cast<int*>(my_mapped_ptr.get()));
// another shared pointer pointing to the shared ints
auto another_share = shared_ints;
}
+0
謝謝,我會研究這一點。我也想讓我的課不可複製。 – user1876942
+0
@ user1876942在這種情況下,具有自定義刪除類型的'unique_ptr'是您的朋友 –
相關問題
- 1. 如何使用複製構造函數
- 2. 複製構造函數
- 3. 複製構造函數bug
- 4. 複製構造函數類
- 5. 複製構造函數
- 6. Cython:複製構造函數
- 7. 複製點構造函數
- 8. doubleLinkedList複製構造函數
- 9. 複製構造函數?
- 10. C++複製構造函數
- 11. Matlab複製構造函數
- 12. 複製構造函數 - C++
- 13. C + +複製構造函數不復制
- 14. 隱式使用轉換構造函數需要複製構造函數
- 15. 矢量 - push_back使用默認的構造函數不復制構造函數
- 16. 拷貝構造函數的地址
- 17. 複製構造函數去基礎構造函數並覆蓋複製值
- 18. 在複製構造函數中使用memcpy複製QThread指針
- 19. 使用clone()複製字段與複製構造函數Java
- 20. Variadic模板構造函數和複製構造函數
- 21. 刪除複製構造函數break繼承構造函數
- 22. 構造函數或複製構造函數?
- 23. 字符串類的構造函數和複製構造函數
- 24. 利用複製構造函數=超載
- 25. 通用複製構造函數
- 26. 複製構造函數未調用?
- 27. Haskell「複製構造函數」調用
- 28. 複製構造函數調用C++
- 29. 複製構造函數的調用
- 30. 通用集類 - 複製構造函數
爲什麼底片?提供一些反饋。 – user1876942
我想,否定的,因爲沒有足夠的信息讓任何人回覆你的querry。 –
這是一個普遍的問題。你可以把一個mmap指針放到拷貝構造函數中嗎?你需要什麼信息? – user1876942