Can I new[], then cast the pointer, then delete[]

2019-03-12 21:48发布

In my code I have effectively the following:

wchar_t* buffer = new wchar_t[size];
// bonus irrelevant code here
delete[] reinterpret_cast<char*>( buffer );

Types in question are all built-in and so they have trivial destructors. In VC++ the code above works allright - new[] just allocates memory, then delete[] just frees it.

Is it acceptable in C++? Is it undefined behaviour?

7条回答
该账号已被封号
2楼-- · 2019-03-12 22:16

Why are you using reinterpret_cast<..>? If you are writing something in pure C++, then you don't need reinterpret cast. In your case you are not allocating the memory for a object. You are allocating the memory for wchar_t. Why don't use to string instead of array of wchar_t?

查看更多
登录 后发表回答