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:
I think ATL collection classes are doing this in order to instantiate an element on already existing/allocated memory block.
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 :)
sure it's the same as reinterpret_cast, but you have the benefit of confusing everyone who reads the code ;)
Post a Comment