problem about placement-new-Collection of common programming errors


  • Daniel Daranas
    c++ placement-new
    Is this safe? I’m not using any virtual functions in my actual implementation, but I’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 char[sizeof(T)]; new (buf) T; T * t = (T *)buf; //code… //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->~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

  • Mateusz
    c++ placement-new explicit-constructor
    recently 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…are there other differences? Regards Mateusz

  • bluescarni
    c++ pointers placement-new
    Is the following legal C++ with well-defined behaviour?class my_class { … };int main() {char storage[sizeof(my_class)];new ((void *)storage) my_class(); }Or is this problematic because of pointer casting/alignment considerations?

  • LorenVS
    c++ templates gcc c++0x placement-new
    Hmm… Title is a bit of a mouthful, but I’m really not sure which part of this is causing issues, I’ve run through it a ton of times, and can’t pinpoint why…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’s template list… It’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

  • BlueRaja – Danny Pflughoeft
    c++ malloc new-operator placement-new
    I’ve been looking into this for the past few days, and so far I haven’t really found anything convincing other than dogmatic arguments or appeals to tradition (i.e. “it’s the C++ way!”).If I’m creating an array of objects, what is the compelling reason (other than ease) for using:#define MY_ARRAY_SIZE 10// …my_object * my_array=new my_object [MY_ARRAY_SIZE];for (int i=0;i<MY_ARRAY_SIZE;++i) my_array[i]=my_object(i);over#define MEMORY_ERROR -1 #define MY_ARRAY_SIZE 10// …my_object * my_a

  • Mooing Duck
    c++ templates virtual placement-new
    class base {int a; protected:template<class T>class derived; public:base() {}virtual ~base() {}virtual void func() {}static base* maker(); };template <class T> class base::derived : public base { public: derived() {}virtual ~derived() {}virtual void func() {this->~derived(); //<–is this legal?new (this) derived<int>(); //<–is this legal?} };base* base::maker() {return new derived<double>(); }int main() {base* p = base::maker(); //p is derivedA<double>

  • FredOverflow
    c++ constructor destructor object-lifetime placement-new
    I have encountered a slightly unusual problem. Consider the following code:class parser {lexer lex;public:node_ptr parse(const std::string& expression){lex.init(expression.begin(), expression.end());// …// 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 “default” state. Usually, one should intialize a member during construct

  • balki
    c++ c++11 constexpr placement-new opaque-pointers
    I want to exclude some headers from my include chain after having used them. From what I know there is no exclude “header.h” in c++11.Pseudo Code Wishful thinking:#include “the_bad_header.h” //long includechain with later unused declarations class bulky { … }; 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’t argue this is not a serious problem. The Example is

  • Kristian Spangsege
    c++ uninitialized placement-new
    Does 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 <cstdlib> #include <cassert>struct Foo {int alpha; // NOTE: Uninitializedint beta = 0; };int main() {void* p = std::malloc(sizeof (Foo));int i = some_random_integer();static_cast<Foo*>(p)->alpha = i;new (p) Foo;assert(static_cast<Foo*>(p)->alpha == i); }Is the ans

  • Jim Hunziker
    c++ memory-allocation placement-new
    I’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

  • jogojapan
    c++ vector c++11 std placement-new
    There 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()

  • user1210290
    c++ placement-new reinterpret-cast
    From 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’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’ll call Message. I know of two ways to proceed

  • HostileFork
    c++ undefined-behavior language-lawyer placement-new
    (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…so bear that in mind!)Here’s a contrived class:class foo { private:int bar; public:foo(int bar) : bar (bar){ std::cout << “construct foo #” << bar << std::endl; }~foo(){ std::cout << “destruct foo #” << bar << std::endl; } };…which I will allocate like this:// Note: for alignment, do

  • Nawaz
    c++ malloc destructor new-operator placement-new
    I’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 << “destructor called” << endl;}void destroyApproach1() { this->~Sample(); }void destroyApproach2() { delete this; } };void destroyApproach3(Sample *_this) {delete _this; }void TestUsingNew() {Sample *pSample[] = { new Sample(), new Sample()

  • iammilind
    c++ destructor placement-new explicit-destructor-call
    Here by “simple”, I mean a class with non-virtual empty destructor or POD type.Typical example:char buffer[SIZE]; T *p = new(buffer) T; … p->~T(); // <—- always ?What happens if we don’t call the explicit destructor on p? I don’t think it is undefined behavior or memory leak. Is there any problem with reusing buffer ?

  • Kerrek SB
    c++ placement-new
    Sometimes it’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 (&x) T(22, Brown, true); // in with the new!// … }At the end of the scope, the destructor will run once again and all seems well. (Let’s also say T is a bit special and doesn’t like being assigned, let alone swapped.) But something tells me that it’s not always without risk to destroy everything and try again. Is there a p

  • user1042389
    c++ constructor destructor placement-new
    In 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

  • iammilind
    c++ memory-deallocation placement-new
    Consider the following code,#include “iostream” #include “conio.h”using namespace std;class sample {private:int i;public:sample(int ii=0) : i(ii){ cout<<“Constructing Object”<<endl; }~sample() { cout<<“Destructing Object”<<endl; }void* operator new(size_t nSize, void* loc){cout <<“Inside new”<<endl;cout <<loc<<endl;return loc;}void operator delete(void* ptr){cout <<“Inside delete”<<endl;free(ptr);} };int main() {

  • 0xbadf00d
    c++ pod placement-new
    Given 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 < n; ++i)new (&p[i].member) other_pod(whatever);

  • bitmask
    c++ placement-new construction
    I’m asking if (and why) the following approach is a) legal and b) moral. I’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

  • icedwater
    c++ allocation placement-new delete-operator
    This question already has an answer here:What uses are there for “placement new”?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)<=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 “memory” buffer is deallocated by just “deleting obj”? Or it is b

  • jcwenger
    c++ operator-overloading placement-new
    Background: I have a complicated class with many variables. I have a sound and tested copy constructor:Applepie::Applepie( const Applepie &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’s being replaced, and etc etc etc, can I s

  • PiotrNycz
    c++ g++ powerpc placement-new
    I 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 – 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->~A(); }__alignof(A) == 4, (buffer + 1) is not aligned to 4. But everything works fine – full example here: http://ideone.com/jBrk

  • FredOverflow
    c++ arrays initialization dynamic-memory-allocation placement-new
    Just out of curiosity, is the following legal?X* p = static_cast<X*>(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)->~X(); (q + 1)->~X(); (q + 0)->~X(); operator delete[](q);

  • keveman
    c++ new-operator placement-new
    I 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

  • eXXXXXXXXXXX
    c++ placement-new
    #include <stdlib.h> #include <iostream> #include <vector> #include <string> class A { public:std::string s;A(){s = “string”;new(this)A(*this);} }; int main() {A a;std::cout<<a.s;return 0; }I get empty string in output. What does the C++ standard say about such behaviour?

  • Xeo
    c++ this undefined-behavior placement-new
    In 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 <iostream>class X{int _i; public: X() : _i(0) { std::cout << “X()\n”; }X(int i) : _i(i) { std::cout << “X(int)\n”; }~X(){ std::cout << “~X()\n”; }void foo(){this->~X();new (this) X(5);}void print_i(){std::cout << _i << “\n”;} };int main(){X x;x.foo();// mock random sta

Web site is in building