Opaque reference instead of PImpl. Is it possible?

只愿长相守 提交于 2019-12-11 03:32:37

问题


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++.


回答1:


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.



来源:https://stackoverflow.com/questions/10784281/opaque-reference-instead-of-pimpl-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!