(Note: this question was motivated by trying to come up with preprocessor hackery to generate a no-op allocation to answer this other question:
...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, don't use char* buffer with new char[sizeof(foo)] !
void* buffer = operator new(sizeof(foo));
foo* p1 = new (buffer) foo(1);
foo* p2 = new (buffer) foo(2);
/* p1->~foo(); */ /* not necessary per spec and problematic in gen. case */
p2->~foo();
On the gcc I've got around, I get the "expected" result:
construct foo #1
construct foo #2
destruct foo #2
Which is great, but could the compiler/runtime reject this as an abuse and still be on the right side of the spec?
How about with threading? If we don't actually care about the contents of this class (let's say it's just a dummy object anyway) will it at least not crash, such as in the even simpler application which motivated this with a POD int?