2011-02-09

Reusing bits

I was cleaning my projects directory and I have stumbled upon a small piece of code which I thought might interest others.

The small piece of code was about changing a private data member from outside the object, using normal C++, without using reintepret_cast or hacks like #define class struct


#include <iostream>

class Pi
{
    double pi_;
public:
    Pi() : pi_(3.1514f)
    {
    }

    double GetValue() const
    {
        return pi_;
    }
};

struct Pie
{
    double pie_;
};

int main()
{
    using std::cout;
    using std::endl;

    Pi pi;
   
    cout << "Pi: " << pi.GetValue() << endl;

    Pie* p = new (&pi) Pie;
   
    p->pie_ = 4.0f;

    cout << "Pi: " << pi.GetValue() << endl;
}

I have highlighted the line which does the trick. This trick is called placement new.

3 comments:

Anonymous said...

I think ATL collection classes are doing this in order to instantiate an element on already existing/allocated memory block.

Anonymous said...

If you write a new memory allocator in C++ you definitely use the placement new. I used around here: https://code.google.com/p/heavy-malloc/ - I think you can find other examples too :)
Neat trick, but it's actually the same thing as a cast/reinterpret_cast :)

radu said...

sure it's the same as reinterpret_cast, but you have the benefit of confusing everyone who reads the code ;)