Have more time off today, and decided I'd test an interesting little idiom out to help with const-correctness. It turns out you can actually do a lot of neat (and admittedly very dangerous) tricks with placement new, up to and including re-instantiating objects using the this pointer. As far as I can tell, there do not appear to be any adverse effects so long as the idiom itself is used correctly; since we're using the this pointer from an already-constructed object we're guaranteed to have proper alignment and size and recreating the object in this fashion doesn't appear to muck up any lifetimes, etc. Code:
main.cpp
#include "SomeClass.h"
#include <iostream>
int main()
{
{
SomeClass stackClass;
stackClass.ReInstantiate();
stackClass.WriteSomeData();
}
std::cout << "---" << std::endl;
SomeClass* heapPtr = new SomeClass();
heapPtr->ReInstantiate();
heapPtr->WriteSomeData();
delete heapPtr;
int i;
std::cin >> i;
return 0;
}
SomeClass.h:
#pragma once
class SomeClass
{
public:
SomeClass();
virtual ~SomeClass();
void ReInstantiate();
void WriteSomeData();
private:
char* const dataChunk;
const unsigned long moreData;
const bool evenMoreData;
};
SomeClass.cpp:
#include "SomeClass.h"
#include <memory>
#include <iostream>
SomeClass::SomeClass() : dataChunk(new char[32]),
moreData(0),
evenMoreData(true)
{
std::cout << "SomeClass()" << std::endl;
}
SomeClass::~SomeClass()
{
std::cout << "~SomeClass()" << std::endl;
if(dataChunk)
delete[] dataChunk;
}
void SomeClass::WriteSomeData()
{
std::cout << "WriteSomeData()" << std::endl;
for( size_t i = 0; i < 32; i++ )
{
dataChunk = '3';
}
}
void SomeClass::ReInstantiate()
{
std::cout << "ReInstantiate()" << std::endl;
//void* thisPtr = this;
this->~SomeClass();
new(this) SomeClass;
}
I would appreciate if someone could test this on something other than MSVC9 (VS2008) to see what happens. No guarantees if it's actually even practical or actually works elsewhere, it just seems interesting.
clb: At the end of 2012, the positions of jupiter, saturn, mercury, and deimos are aligned so as to cause a denormalized flush-to-zero bug when computing earth's gravitational force, slinging it to the sun.