Delphi - 智能指针构造函数的奇怪行为

时间:2017-02-15 16:00:52

标签: delphi constructor package gdi+ smart-pointers

我正在开发一个包含多个软件包的项目。在我的一个基础包中,我声明了一个智能指针,就像那样(这里是完整的代码):

unit UTWSmartPointer;

interface

type
    IWSmartPointer<T> = reference to function: T;

    TWSmartPointer<T: class, constructor> = class(TInterfacedObject, IWSmartPointer<T>)
    private
        m_pInstance: T;

    public
        constructor Create; overload; virtual;

        constructor Create(pInstance: T); overload; virtual;

        destructor Destroy; override;

        function Invoke: T; virtual;
    end;

implementation
//---------------------------------------------------------------------------
constructor TWSmartPointer<T>.Create;
begin
    inherited Create;

    m_pInstance := T.Create;
end;
//---------------------------------------------------------------------------
constructor TWSmartPointer<T>.Create(pInstance: T);
begin
    inherited Create;

    m_pInstance := pInstance;
end;
//---------------------------------------------------------------------------
destructor TWSmartPointer<T>.Destroy;
begin
    m_pInstance.Free;
    m_pInstance := nil;

    inherited Destroy;
end;
//---------------------------------------------------------------------------
function TWSmartPointer<T>.Invoke: T;
begin
    Result := m_pInstance;
end;
//---------------------------------------------------------------------------

end.

稍后在我的项目中(以及另一个包中),我将这个智能指针与GDI +对象(TGpGraphicsPath)一起使用。我声明了这样的图形路径:

...
pGraphicsPath: IWSmartPointer<TGpGraphicsPath>;
...
pGraphicsPath := TWSmartPointer<TGpGraphicsPath>.Create();
...

但是,执行代码时屏幕上没有任何内容。我没有错误,没有异常或访问冲突,只是一个空白页面。但是,如果我只是改变我的代码:

...
pGraphicsPath: IWSmartPointer<TGpGraphicsPath>;
...
pGraphicsPath := TWSmartPointer<TGpGraphicsPath>.Create(TGpGraphicsPath.Create);
...

然后一切都变好了,我的路径完全按照预期绘制。但我无法弄清楚为什么第一个构造函数不能按预期工作。有人可以向我解释这种奇怪的行为吗?

此致

1 个答案:

答案 0 :(得分:4)

这是一个非常复杂的陷阱,你已陷入其中。当你写:

TGpGraphicsPath.Create

您可能认为您正在调用无参数构造函数。但事实并非如此。你实际上是在调用这个构造函数:

constructor Create(fillMode: TFillMode = FillModeAlternate); reintroduce; overload;      

您不提供参数,因此默认值由编译器提供。

在你的智能指针类中写下:

T.Create

这实际上是在调用无参数构造函数。但那是由TObject定义的构造函数。使用该构造函数时,TGPGraphicsPath实例未正确初始化。

如果要使用constructor泛型约束,还必须确保始终使用可以使用无参数构造函数正确构造的类。不幸的是,你TGPGraphicsPath不符合要求。事实上,这类课程占优势。

为了避免显式调用构造函数,你可以在这里做很多事情。对于这个特定的类,你的智能指针类几乎不可能计算出要调用的构造函数。

我的建议是远离constructor泛型约束,并强制智能指针类的使用者显式实例化实例。

这是一个非常常见的问题 - 我在不到一周前回答了类似的问题:Why does a deserialized TDictionary not work correctly?

相关问题