Home  >  Q&A  >  body text

c++ - What is the specific implementation of this reserved by library placement?

    #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 newThe 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:

  1. 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.

  2. 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:

怪我咯怪我咯2736 days ago787

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-16 13:32:16

    /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

    reply
    0
  • Cancelreply