#define __PLACEMENT_NEW_INLINE
_Ret_notnull_ _Post_writable_byte_size_(_Size)
inline void* __CRTDECL operator new(size_t _Size, _Writable_bytes_(_Size) void* _Where) throw()
{
(void)_Size;
return _Where;
}
I encountered it when learning various forms of operator new (c++ primer didn’t explain much), but I couldn’t understand the role of this function, such as how to use this function call to implement placement new
The construction effect, such as thistwo *abc = new(m) two(10);
(Although I saw this construction, it actually calls the above function), and. The test example is as follows ( The problem has been commented):
// test_.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
class one
{
public:
int x;
int y = 0;
};
class two
{
public:
static int p;
two(int a_) : a{a_} {}
two()
{
a = 2;
b = 3;
}
private:
class one o;
int a;
int b = 1;
};
int two::p = 66;
int main()
{
void *m = ::operator new(20, std::nothrow);
two *www = NULL;
::operator new(100, www); //注释处是本提问的问题所在, 也是上面那个代码的入口
new(www) two;
decltype(auto) x = two::p;
two *abc = new(m) two(10);
int df = 1;
_CrtDumpMemoryLeaks();
return 0;
}
Here I will further simplify and detail the problem:
Why this function can achieve the effect of construction? two *abc = new(m) two(10);
For example, I don’t have it (or I don’t know how to enter it in step into ) can clearly see the specific implementation, although I know that abstraction means that the object two(10)
is constructed in place.
If I use main()
to directly call the function in the function comment to achieve in-place construction, how should I modify the parameters and pass in the parameters to achieve two *abc = new (m) two(10);
Same effect?
Note:
One of my initial guesses was that the _Where pointer passed in should be a pointer to an already constructed object, but to implement this, there needs to be an object already, and placement new
It should be violated.
/q/10... @felix Dashi has already given an answer to this question, I just saw it. I will think about it and search for related content