相关疑难解决方法(0)

通过不同类型的指针删除缓冲区?

说我有以下C++:

char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;
Run Code Online (Sandbox Code Playgroud)

根据C++标准,这是安全的吗?我需要回头char*再使用delete[]吗?我知道它在大多数C++编译器中都有效,因为它是普通的普通数据,没有析构函数.它保证安全吗?

c++ pointers memory-management

10
推荐指数
2
解决办法
1906
查看次数

将`char*`与`delete`解除分配 - 内存泄漏?

template<typename T> char* allocateSomething()
{
    return reinterpret_cast<char*>(std::allocator<T>{}.allocate(1));
}

void deallocateSomething(char* mPtr) { delete mPtr; }

struct TestType { ... };

int main()
{
    char* ptr{allocateSomething<TestType>()};
    deallocateSomething(ptr);   
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

是否可以保证deallocateSomething(ptr)释放所有已分配的字节,即使它typename T在调用时不知道使用的是什么allocateSomething<T>()

还是有必要模板化deallocateSomething

编辑:我手动处理对象的构造/销毁.


编辑2:这会正常工作吗?

template<typename T> char* allocateSomething()
{
    return reinterpret_cast<char*>(std::malloc(sizeof(T)));
}

void deallocateSomething(char* mPtr) { std::free(mPtr); }

// ...
Run Code Online (Sandbox Code Playgroud)

c++ memory memory-management c++11

-2
推荐指数
1
解决办法
208
查看次数

标签 统计

c++ ×2

memory-management ×2

c++11 ×1

memory ×1

pointers ×1