{"id":4148,"date":"2014-03-30T08:22:31","date_gmt":"2014-03-30T08:22:31","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/problem-about-placement-new-collection-of-common-programming-errors\/"},"modified":"2014-03-30T08:22:31","modified_gmt":"2014-03-30T08:22:31","slug":"problem-about-placement-new-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/problem-about-placement-new-collection-of-common-programming-errors\/","title":{"rendered":"problem about placement-new-Collection of common programming errors"},"content":{"rendered":"<ul>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/HW6VJ.jpg?s=32&amp;g=1\" \/><br \/>\nDaniel Daranas<br \/>\nc++ placement-new<br \/>\nIs this safe? I&#8217;m not using any virtual functions in my actual implementation, but I&#8217;m tempted to believe that even if I was, it would still be safe.class Foo {Foo(){\/\/ initialize things}Foo( int ){new ( this ) Foo();} }<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/12a5de18c6ec419a232a629a631c4612?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nArmen Tsirunyan<br \/>\nc++ templates new-operator destructor placement-new<br \/>\nchar * buf = new char[sizeof(T)]; new (buf) T; T * t = (T *)buf; \/\/code&#8230; \/\/here I should destruct *t but as it is argument of template and can be \/\/instantiated via basic types as well (say int) so such code \/*t-&gt;~T();*\/ \/\/is incorrect (maybe correct? Strange, but it works on VS 2005 for basic types.) \/\/and this code \/*delete t;*\/ \/\/crashes the program. delete [] buf;So what is correct way to destruct t?P.S. The code above is only for describing my problem, and have not real relationship<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/e99f232d2cf75482b567e84c7557331d?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nMateusz<br \/>\nc++ placement-new explicit-constructor<br \/>\nrecently I have come across these two ways of creating an object in a specific place in memory:1. void* mem = malloc(sizeof(T)); T* obj = new(mem) T();2.T* obj = (T*)malloc(sizeof(T)); *obj = T();The second way is a bit shorter&#8230;are there other differences? Regards Mateusz<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/4dd67eab56c9687453c13002faf3df36?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nbluescarni<br \/>\nc++ pointers placement-new<br \/>\nIs the following legal C++ with well-defined behaviour?class my_class { &#8230; };int main() {char storage[sizeof(my_class)];new ((void *)storage) my_class(); }Or is this problematic because of pointer casting\/alignment considerations?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/42b1babf030b89a9d916db8a0e416d0e?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nLorenVS<br \/>\nc++ templates gcc c++0x placement-new<br \/>\nHmm&#8230; Title is a bit of a mouthful, but I&#8217;m really not sure which part of this is causing issues, I&#8217;ve run through it a ton of times, and can&#8217;t pinpoint why&#8230;The idea is for a single Choice instance to be able to store any one value of any of the types passed in to it&#8217;s template list&#8230; It&#8217;s kind of like a union, except it keeps track of the type being stored, and considers values of each type to be distinct, which allows it to get around the C++ constraints on constructors in union members.It<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/460167b95ff5a363d3977ddb56cfe074?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nBlueRaja &#8211; Danny Pflughoeft<br \/>\nc++ malloc new-operator placement-new<br \/>\nI&#8217;ve been looking into this for the past few days, and so far I haven&#8217;t really found anything convincing other than dogmatic arguments or appeals to tradition (i.e. &#8220;it&#8217;s the C++ way!&#8221;).If I&#8217;m creating an array of objects, what is the compelling reason (other than ease) for using:#define MY_ARRAY_SIZE 10\/\/ &#8230;my_object * my_array=new my_object [MY_ARRAY_SIZE];for (int i=0;i&lt;MY_ARRAY_SIZE;++i) my_array[i]=my_object(i);over#define MEMORY_ERROR -1 #define MY_ARRAY_SIZE 10\/\/ &#8230;my_object * my_a<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/a0638389439eea6b5dc936abccbe3c68?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nMooing Duck<br \/>\nc++ templates virtual placement-new<br \/>\nclass base {int a; protected:template&lt;class T&gt;class derived; public:base() {}virtual ~base() {}virtual void func() {}static base* maker(); };template &lt;class T&gt; class base::derived : public base { public: derived() {}virtual ~derived() {}virtual void func() {this-&gt;~derived(); \/\/&lt;&#8211;is this legal?new (this) derived&lt;int&gt;(); \/\/&lt;&#8211;is this legal?} };base* base::maker() {return new derived&lt;double&gt;(); }int main() {base* p = base::maker(); \/\/p is derivedA&lt;double&gt;<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/082b8ee2b0aebb430b8d4d98e6a5c32f?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nFredOverflow<br \/>\nc++ constructor destructor object-lifetime placement-new<br \/>\nI have encountered a slightly unusual problem. Consider the following code:class parser {lexer lex;public:node_ptr parse(const std::string&amp; expression){lex.init(expression.begin(), expression.end());\/\/ &#8230;\/\/ call some helper methods\/\/ return the result}private:\/\/ lots of small helper methods, many of them accessing lex };The parse method initializes the lexer with an init method. Before that, the lexer is in an unusable &#8220;default&#8221; state. Usually, one should intialize a member during construct<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/78e87615823ef2ad514ccd618fd22f21?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nbalki<br \/>\nc++ c++11 constexpr placement-new opaque-pointers<br \/>\nI want to exclude some headers from my include chain after having used them. From what I know there is no exclude &#8220;header.h&#8221; in c++11.Pseudo Code Wishful thinking:#include &#8220;the_bad_header.h&#8221; \/\/long includechain with later unused declarations class bulky { &#8230; }; constexpr std::size_t bulkysize = sizeof(bulky); forget everything included and class bulky and remember only bulkysizeMy example where the problem becomes evident follows. Please don&#8217;t argue this is not a serious problem. The Example is<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/c499f7c44a009b3d9aba5f6990794f1f?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nKristian Spangsege<br \/>\nc++ uninitialized placement-new<br \/>\nDoes the C++ standard guarantee that uninitialized POD members retain their previous value after a placement new?Or more precisely, will the following assert always be satisfied according to C++11?#include &lt;cstdlib&gt; #include &lt;cassert&gt;struct Foo {int alpha; \/\/ NOTE: Uninitializedint beta = 0; };int main() {void* p = std::malloc(sizeof (Foo));int i = some_random_integer();static_cast&lt;Foo*&gt;(p)-&gt;alpha = i;new (p) Foo;assert(static_cast&lt;Foo*&gt;(p)-&gt;alpha == i); }Is the ans<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/1f771c9778a31cd691a6ae597b6326f9?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nJim Hunziker<br \/>\nc++ memory-allocation placement-new<br \/>\nI&#8217;m using C++, and I have the following structures:struct ArrayOfThese {int a;int b; };struct DataPoint {int a;int b;int c; };In memory, I want to have 1 or more ArrayOfThese elements at the end of each DataPoint. There are not always the same number of ArrayOfThese elements per DataPoint.Because I have a ridiculous number of DataPoints to assemble and then stream across a network, I want all my DataPoints and their ArrayOfThese elements to be contiguous. Wasting space for a fixed number of the<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/ef170cdb4e468f86c79ba477352a5f53?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\njogojapan<br \/>\nc++ vector c++11 std placement-new<br \/>\nThere are two existing questions about replacing vector elements that are not assignable:C++ Use Unassignable Objects in Vector How to push_back without operator=() for const members?A typical reason for an object to be non-assignable is that its class definition includes const members and therefore has its operator= deleted.std::vector requires that its element type be assignable. And indeed, at least using GCC, neither direct assignment (vec[i] = x;), nor a combination of erase() and insert()<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/21c699511f99794f1b69f5412e64d4c4?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nuser1210290<br \/>\nc++ placement-new reinterpret-cast<br \/>\nFrom reading this post, it is clear that placement news in c++ are used to call a class constructor on a pre-allocated memory location. In the case that the memory is already initialized, is a placement new or a reinterpret_cast more appropriate?For example, let&#8217;s say I read a raw stream of bytes representing a framed message from a TCP socket. I put this stream into a framesync and retrieve a buffer of a known size that represents my class, which I&#8217;ll call Message. I know of two ways to proceed<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/4718212e95d7adea8c412379e7f542e9?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nHostileFork<br \/>\nc++ undefined-behavior language-lawyer placement-new<br \/>\n(Note: this question was motivated by trying to come up with preprocessor hackery to generate a no-op allocation to answer this other question:C++ Macro that accent new object&#8230;so bear that in mind!)Here&#8217;s a contrived class:class foo { private:int bar; public:foo(int bar) : bar (bar){ std::cout &lt;&lt; &#8220;construct foo #&#8221; &lt;&lt; bar &lt;&lt; std::endl; }~foo(){ std::cout &lt;&lt; &#8220;destruct foo #&#8221; &lt;&lt; bar &lt;&lt; std::endl; } };&#8230;which I will allocate like this:\/\/ Note: for alignment, do<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/acebaaf02be9bbc7319c51af806f9ec2?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nNawaz<br \/>\nc++ malloc destructor new-operator placement-new<br \/>\nI&#8217;m just curious to know if there is any significant\/serious difference in these three approaches of invoking destructor. Consider the following code. Please also consider the two cases mentioned in main().class Sample { public:~Sample(){cout &lt;&lt; &#8220;destructor called&#8221; &lt;&lt; endl;}void destroyApproach1() { this-&gt;~Sample(); }void destroyApproach2() { delete this; } };void destroyApproach3(Sample *_this) {delete _this; }void TestUsingNew() {Sample *pSample[] = { new Sample(), new Sample()<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/73c478b60c371abe43bb7ac15ff3666d?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\niammilind<br \/>\nc++ destructor placement-new explicit-destructor-call<br \/>\nHere by &#8220;simple&#8221;, I mean a class with non-virtual empty destructor or POD type.Typical example:char buffer[SIZE]; T *p = new(buffer) T; &#8230; p-&gt;~T(); \/\/ &lt;&#8212;- always ?What happens if we don&#8217;t call the explicit destructor on p? I don&#8217;t think it is undefined behavior or memory leak. Is there any problem with reusing buffer ?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/a18405dd4b022837867d1f5453a05f41?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nKerrek SB<br \/>\nc++ placement-new<br \/>\nSometimes it&#8217;s nice to start over. In C++ I can employ this following simple manoeuvre:{T x(31, Blue, false);x.~T(); \/\/ enough with the old x::new (&amp;x) T(22, Brown, true); \/\/ in with the new!\/\/ &#8230; }At the end of the scope, the destructor will run once again and all seems well. (Let&#8217;s also say T is a bit special and doesn&#8217;t like being assigned, let alone swapped.) But something tells me that it&#8217;s not always without risk to destroy everything and try again. Is there a p<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/e806e0fd3a5599df891da0190e644088?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nuser1042389<br \/>\nc++ constructor destructor placement-new<br \/>\nIn the code that follows, the object sub in class C is constructed twice. The first construction calls the default ctor Sub() and the second construction uses placement new to reconstruct this object in the same address.Therefore the destructors are also called twice. The first call uses the direct call to the Sub dtor in ~C() and the second call is invoked after the end of main(), I believe, by the atexit() function. Given that the object sub is reconstructed at the same address, how does the<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/73c478b60c371abe43bb7ac15ff3666d?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\niammilind<br \/>\nc++ memory-deallocation placement-new<br \/>\nConsider the following code,#include &#8220;iostream&#8221; #include &#8220;conio.h&#8221;using namespace std;class sample {private:int i;public:sample(int ii=0) : i(ii){ cout&lt;&lt;&#8220;Constructing Object&#8221;&lt;&lt;endl; }~sample() { cout&lt;&lt;&#8220;Destructing Object&#8221;&lt;&lt;endl; }void* operator new(size_t nSize, void* loc){cout &lt;&lt;&#8220;Inside new&#8221;&lt;&lt;endl;cout &lt;&lt;loc&lt;&lt;endl;return loc;}void operator delete(void* ptr){cout &lt;&lt;&#8220;Inside delete&#8221;&lt;&lt;endl;free(ptr);} };int main() {<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/4dbfd610336a9667e0b11eac69b9cc34?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\n0xbadf00d<br \/>\nc++ pod placement-new<br \/>\nGiven any POD type, is it recommendable to do something like that:any_pod* p = new any_pod[n]; for (std::size_t i = 0; i &lt; n; ++i)new (&amp;p[i].member) other_pod(whatever);<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/ee7e736eeb33c4b03d4a5e6e813a9abc?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nbitmask<br \/>\nc++ placement-new construction<br \/>\nI&#8217;m asking if (and why) the following approach is a) legal and b) moral. I&#8217;m asking with emphasis on C++03, but notes on C++11 are welcome, too. The idea is to prevent derived classes that could themselves be default constructible from implementing stupid B::B(int foo) : A(foo) {} constructors.class Base {private:int i;Base(int i) : i(i) {}protected:Base() {}public:static Base* create(int i); }; class Derived : public Base { };Base* Base::create(int i) {Derived* d = new Derived();Base* b = stati<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/bd5c864fec9209546b3da1cf717193b0?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nicedwater<br \/>\nc++ allocation placement-new delete-operator<br \/>\nThis question already has an answer here:What uses are there for \u201cplacement new\u201d?19 answersAssume I want to allocate only 256 bytes memory blockschar * memory = new char[256];than I use placement new to create a FooBar object (sizeof(Foobar)&lt;=256)FooBar * obj = new (memory) FooBar();doesdelete obj; \/\/this also calls the destructor of FooBardelete all the 256 bytes of memory?Does the standard guarantee that the whole &#8220;memory&#8221; buffer is deallocated by just &#8220;deleting obj&#8221;? Or it is b<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/FDosm.jpg?s=32&amp;g=1\" \/><br \/>\njcwenger<br \/>\nc++ operator-overloading placement-new<br \/>\nBackground: I have a complicated class with many variables. I have a sound and tested copy constructor:Applepie::Applepie( const Applepie &amp;copy) : m_crust(copy.m_crust), m_filling(copy.m_filling) { }Some of the member variable copy constructors called in the intializer list perform allocation.Question: I need to create operator=. Rather than duplicating the existing constuctor with assignment instead of initialization list, and freeing memory that&#8217;s being replaced, and etc etc etc, can I s<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/3878980c7836d9e36f3a9ac100ff36a8?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nPiotrNycz<br \/>\nc++ g++ powerpc placement-new<br \/>\nI read this When should I worry about alignment? but I am still do not know if I have to worry about not aligned pointer returned by placement new operator &#8211; like in this example:class A { public:long double a;long long b;A() : a(1.3), b(1234) {} };char buffer[64];int main() {\/\/ (buffer + 1) used intentionally to have wrong alignmentA* a = new (buffer + 1) A(); a-&gt;~A(); }__alignof(A) == 4, (buffer + 1) is not aligned to 4. But everything works fine &#8211; full example here: http:\/\/ideone.com\/jBrk<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/082b8ee2b0aebb430b8d4d98e6a5c32f?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nFredOverflow<br \/>\nc++ arrays initialization dynamic-memory-allocation placement-new<br \/>\nJust out of curiosity, is the following legal?X* p = static_cast&lt;X*&gt;(operator new[](3 * sizeof(X))); new(p + 0) X(); new(p + 1) X(); new(p + 2) X();delete[] p; \/\/ Am I allowed to use delete[] here? Or is it undefined behavior?Similarly:X* q = new X[3]();(q + 2)-&gt;~X(); (q + 1)-&gt;~X(); (q + 0)-&gt;~X(); operator delete[](q);<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/ac5c46a75d24d0268e1b779977ad7e58?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nkeveman<br \/>\nc++ new-operator placement-new<br \/>\nI have the following code :struct foo {}; void bar(foo *d) {new(d) foo(*d); }Does the expression new(d) foo(*d) leave the object pointed to by d unchanged? More specifically, is the above true if the class foo and all the objects contained recursively within it only have trivial copy constructors, then does new(d) foo(*d) leave *d unchanged? A situation in which that is not true could be, new first zeroes out the memory before calling the copy constructor. Are there such clauses in the C++ langu<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/15e4a648de45b3005f2f5b891f4e6242?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\neXXXXXXXXXXX<br \/>\nc++ placement-new<br \/>\n#include &lt;stdlib.h&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; class A { public:std::string s;A(){s = &#8220;string&#8221;;new(this)A(*this);} }; int main() {A a;std::cout&lt;&lt;a.s;return 0; }I get empty string in output. What does the C++ standard say about such behaviour?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/eb538603c2b80ea703e92abf5b45c791?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nXeo<br \/>\nc++ this undefined-behavior placement-new<br \/>\nIn this question of mine, @DeadMG says that reinitializing a class through the this pointer is undefined behaviour. Is there any mentioning thereof in the standard somewhere?Example:#include &lt;iostream&gt;class X{int _i; public: X() : _i(0) { std::cout &lt;&lt; &#8220;X()\\n&#8221;; }X(int i) : _i(i) { std::cout &lt;&lt; &#8220;X(int)\\n&#8221;; }~X(){ std::cout &lt;&lt; &#8220;~X()\\n&#8221;; }void foo(){this-&gt;~X();new (this) X(5);}void print_i(){std::cout &lt;&lt; _i &lt;&lt; &#8220;\\n&#8221;;} };int main(){X x;x.foo();\/\/ mock random sta<\/li>\n<\/ul>\n<p>Web site is in building<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Daniel Daranas c++ placement-new Is this safe? I&#8217;m not using any virtual functions in my actual implementation, but I&#8217;m tempted to believe that even if I was, it would still be safe.class Foo {Foo(){\/\/ initialize things}Foo( int ){new ( this ) Foo();} } Armen Tsirunyan c++ templates new-operator destructor placement-new char * buf = new [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4148","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4148","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=4148"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4148\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=4148"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=4148"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=4148"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}