Reputation: 8126
The PIMPL Idiom is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of. This hides internal implementation details and data from the user of the library.
But is it possible to implement the same making use of reference?
MCanvasFont.h
namespace Impl {
class FontDelegate;
}
class MCanvasFont
{
public:
MCanvasFont();
virtual ~MCanvasFont();
protected:
// Reference count
long m_cRef;
// agg font delegate
const Impl::FontDelegate& m_font;
}
MCanvasFont.cpp
// helpers
#include "ImplHelpers/FontDelegate.h"
MCanvasFont::MCanvasFont()
: m_cRef(1),
m_font(Impl::FontDelegate() )
{
// constructor's body
}
P.S. This code compiles without any problems with G++.
Upvotes: 2
Views: 949
Reputation: 23428
There is an error in your program, and it's in the constructor's initialiser list:
MCanvasFont::MCanvasFont()
: m_cRef(1),
m_font(Impl::FontDelegate() ) // <--- BANG
{
The problem with Impl::FontDelegate()
is that it constructs a temporary object. This won't outlive the constructor - in fact it's actually destroyed before entering the constructor body, as it's lifetime is that of the expression in which it appears. Thus your m_font
reference is instantly invalid.
While you could initialise it using a manually allocated object (*new Impl::FontDelegate()
) you're in undefined territory if that allocation fails unless you have exceptions enabled in your runtime. You'll also still have to delete
the object in your destructor anyway. So the reference really doesn't buy you any advantages, it just makes for some rather unnatural code. I recommend using a const pointer instead:
const Impl::FontDelegate* const m_font;
EDIT: Just to illustrate the problem, take this equivalent example:
#include <iostream>
struct B
{
B() { std::cout << "B constructed\n"; }
~B() { std::cout << "B destroyed\n"; }
};
struct A
{
const B& b;
A() :
b(B())
{
std::cout << "A constructed\n";
}
void Foo()
{
std::cout << "A::Foo()\n";
}
~A()
{
std::cout << "A destroyed\n";
}
};
int main()
{
A a;
a.Foo();
}
If you run this, the output will be:
B constructed
B destroyed
A constructed
A::Foo()
A destroyed
So b
is invalid almost immediately.
Upvotes: 5