{"id":8804,"date":"2021-06-20T09:21:33","date_gmt":"2021-06-20T03:51:33","guid":{"rendered":"https:\/\/python-programs.com\/?p=8804"},"modified":"2021-11-22T18:53:28","modified_gmt":"2021-11-22T13:23:28","slug":"whats-placement-new-operator-and-why-do-we-need-it","status":"publish","type":"post","link":"https:\/\/python-programs.com\/whats-placement-new-operator-and-why-do-we-need-it\/","title":{"rendered":"What\u2019s placement new operator and why do we need it ?"},"content":{"rendered":"
This article is all about placement new operator.<\/p>\n
placement new operator we use to pass a memory address to As we know when we create any object using new operator, then the memory is allocated on the heap.<\/p>\n But, while working sometimes we need to create an object dynamically for which some specific memory location will be allocated.<\/p>\n For example, we do not want new memory to be allocated on heap rather it needs to be allocated on a given memory address. Actually this scenario comes when we work on any embedded product or with shared memory. So, for this requirement we use placement new operator.<\/p>\n Below is an example code to achieve this :<\/strong><\/p>\n Placement new operator and it’s need This article is all about placement new operator. Placement new Operator Need of placement new operator Placement new operator : placement new operator we use to pass a memory address to new as a parameter. This memory is used by the placement new operator to create the object and …<\/p>\nnew<\/code> as a parameter. This memory is used by the placement new operator to create the object and also to call the constructor on it and then returning the same passed address.<\/p>\n
<\/a>Need of placement new operator :<\/h3>\n
int<\/span> * ptr = <\/span>new<\/span> int<\/span>;<\/span><\/pre>\n
\/\/ Program\r\n\r\n#include <iostream>\r\n#include <cstdlib>\r\n#include <new>\r\n\r\nint main()\r\n{\r\n\/\/ Here memory will not be allocated on heap.\r\nint * space = new int[1004];\r\n\/\/ It will use passed spacer to allocate the memory\r\nint * ptr = new(space) int;\r\n*ptr = 7;\r\nstd::cout<<(*ptr)<<std::endl;\r\ndelete [] buffer;\r\nreturn 0;\r\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"