#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;
}
學(xué)operator new的各類(lèi)形式時(shí)遇到它(c++ primer 也沒(méi)有做出多少解釋), 但是看不明白這個(gè)函數(shù)的作用, 比如應(yīng)該如何用這個(gè)函數(shù)調(diào)用來(lái)實(shí)現(xiàn)出placement new
的構(gòu)造效果, 比如這樣two *abc = new(m) two(10);
(雖然我看了這樣構(gòu)造其實(shí)也是調(diào)用了上面的那個(gè)函數(shù)), 和. 測(cè)試用例如下(問(wèn)題之處已注釋):
// 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); //注釋處是本提問(wèn)的問(wèn)題所在, 也是上面那個(gè)代碼的入口
new(www) two;
decltype(auto) x = two::p;
two *abc = new(m) two(10);
int df = 1;
_CrtDumpMemoryLeaks();
return 0;
}
這里我把問(wèn)題進(jìn)一步簡(jiǎn)化和細(xì)致下:
這個(gè)函數(shù)為什么能實(shí)現(xiàn)構(gòu)造的效果, 已 two *abc = new(m) two(10);
為例, 我沒(méi)有(或者說(shuō)不知道怎么在step into進(jìn)去)能看清具體實(shí)現(xiàn), 雖然我知道抽象出來(lái)就是實(shí)現(xiàn)了就地構(gòu)造了two(10)
這個(gè)對(duì)象.
如果用main()
函數(shù)注釋處這樣直接調(diào)用函數(shù)的做法來(lái)實(shí)現(xiàn)就地構(gòu)造, 我該如何修改參數(shù)和傳入?yún)?shù)實(shí)現(xiàn) two *abc = new(m) two(10);
一樣的效果?
附注:
我一開(kāi)始的一個(gè)猜想是傳入的_Where指針應(yīng)該是一個(gè)已經(jīng)構(gòu)造好的對(duì)象的指針, 但是這樣實(shí)現(xiàn)的話(huà)需要已經(jīng)有一個(gè)對(duì)象, 與placement new
應(yīng)該是違背的.
走同樣的路,發(fā)現(xiàn)不同的人生
/q/10... @felix 大濕 已經(jīng)在這個(gè)問(wèn)題里給出解答了, 才看到. 我再琢磨和搜下相關(guān)內(nèi)容