c++ - 这个reserved by library的placement的具体实现是什么呢?

浏览:33日期:2023-03-19

问题描述

#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; }

学operator new的各类形式时遇到它(c++ primer 也没有做出多少解释), 但是看不明白这个函数的作用, 比如应该如何用这个函数调用来实现出placement new的构造效果, 比如这样two *abc = new(m) two(10);(虽然我看了这样构造其实也是调用了上面的那个函数), 和. 测试用例如下(问题之处已注释):

// 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;}

这里我把问题进一步简化和细致下:

这个函数为什么能实现构造的效果, 已 two *abc = new(m) two(10);为例, 我没有(或者说不知道怎么在step into进去)能看清具体实现, 虽然我知道抽象出来就是实现了就地构造了two(10)这个对象.

如果用main()函数注释处这样直接调用函数的做法来实现就地构造, 我该如何修改参数和传入参数实现 two *abc = new(m) two(10);一样的效果?

附注:

我一开始的一个猜想是传入的_Where指针应该是一个已经构造好的对象的指针, 但是这样实现的话需要已经有一个对象, 与placement new应该是违背的.

问题解答

回答1:

/q/10... @felix 大湿 已经在这个问题里给出解答了, 才看到. 我再琢磨和搜下相关内容

相关文章: