在内存中创建一个由void指针指向的对象
Create an object in memory pointed to by a void pointer
如果我有一个void*到一些空闲内存块,我知道至少有sizeof(T)可用,有没有办法在内存的那个位置创建一个类型为T的对象?
我只是想在堆栈上创建一个T对象,然后内存覆盖它,但似乎必须有一个更优雅的方式来做到这一点?
使用new:
#include <new>
void *space;
new(space) T();
请记住在释放内存之前删除它:
((T*)space)->~T();
不要在堆栈上创建对象并对其进行memcpy,这是不安全的,如果对象的地址存储在成员或成员的成员中怎么办?
首先,仅仅知道sizeof(T)
的可用内存量是不够的。此外,您必须知道要分配的对象类型的void指针是正确对齐的。使用不对齐的指针可能会导致性能下降或应用程序崩溃,具体取决于您的平台。
#include <new> // for placement new
#include <stdlib.h> // in this example code, the memory will be allocated with malloc
#include <string> // we will allocate a std::string there
#include <iostream> // we will output it
int main()
{
// get memory to allocate in
void* memory_for_string = malloc(sizeof(string)); // malloc guarantees alignment
if (memory_for_string == 0)
return EXIT_FAILURE;
// construct a std::string in that memory
std::string* mystring = new(memory_for_string) std::string("Hello");
// use that string
*mystring += " world";
std::cout << *mystring << std::endl;
// destroy the string
mystring->~string();
// free the memory
free(memory_for_string);
return EXIT_SUCCESS;
}
相关文章:
- 引用一个已擦除类型(void*)的指针
- 如何将指针从一个void函数传递到另一个C++
- 指针没有更新它在void函数内部指向的值
- 错误:在为指针赋值时,void值没有被忽略
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 如何在 C++ 中将 void 函数传递给 void 指针
- 将通用引用强制转换为可调用的 void 指针,反之亦然
- C++为 void 指针分配一个字符串
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 调用向量的函数,给定向量的指针作为 void *
- 取消引用 void 指针以将值分配给结构
- 为什么新表达式可以正确生成指针类型,即使它应该返回 void*?
- C 与 C++,处理 void** 指针
- reinterpret_cast指向 void(*&)() 的成员函数指针
- 使用 void 指针:void **ptr.. 如何修改共享内存的值?
- 我可以将函数指针 void* 强制转换为 std::function 吗?
- void*不是一个指向对象类型的指针 - void **的铸造错误
- 如何使用空指针(void*)
- 指针(void指针)和函数有一点混淆