开发者

shared_ptr returning an interface

So I'm hacking away at my code trying to turn it in to some half-decent C++0x code using GCC 4.5..

shared_ptr<IEngineLayer*> createEngineLayer(void)
{
    try
    {
        CEngineLayer* engine = new CEngineLayer;
        IEngineLayer* interface = dynamic_cast<IEngineLayer*>(engine);

        return shared_ptr<IEngineLayer*>(interface);
    }
    cat开发者_如何学Goch(std::bad_alloc&)
    {
        // Unable to allocate enough memory for the engine layer.
        return shared_ptr<IEngineLayer*>();
    }
}

And I get this..

shared_ptr_base.h:545:65: error: cannot convert ‘DEngine::IEngineLayer*’ to ‘DEngine::IEngineLayer**’ in initialization

How can I fix this?

(Also, as a side note, will shared_ptr destroy both the interface and the CEngineLayer when nobody is using it anymore?)


A shared_ptr<T> models a pointer to T, a shared_ptr<T *> models a pointer to pointer to T.

Assuming that CEngineLayer is a IEngineLayer, you could change your code to :

shared_ptr<IEngineLayer> createEngineLayer()
{
    try
    {
        return shared_ptr<IEngineLayer>(new CEngineLayer);
    }
    catch(const std::bad_alloc&)
    {
        // Unable to allocate enough memory for the engine layer.
        return shared_ptr<IEngineLayer>();
    }
}

Also note that a 'derived to base' conversion does not require an explicit cast : if CEngineLayer inherits publicly from IEngineLayer, a pointer to CEngineLayer can be implicitly converted to a pointer to IEngineLayer.

Also, as a side note, will shared_ptr destroy both the interface and the CEngineLayer when nobody is using it anymore?

There is a single object whose type is CEngineLayer which, if the destructor in IEngineLayer is virtual (and it should be), will be correctly destroyed when the reference count reaches 0.


Return a shared_ptr<IEngineLayer> instead.

The cast isn't needed either:

shared_ptr<IEngineLayer> createEngineLayer()
{
    try
    {
        CEngineLayer* engine = new CEngineLayer;

        return shared_ptr<IEngineLayer>(engine);
    }
    catch(std::bad_alloc&)
    {
        // Unable to allocate enough memory for the engine layer.
        return shared_ptr<IEngineLayer>();
    }
}


You could also use make_shared, which is from a performance perspective better:

std::shared_ptr<IEngineLayer> createEngineLayer(void)
{
    return std::make_shared<CEngineLayer>();
}

Also be are that the following code creates a memory leak:

std::shared_ptr<IEngineLayer> createEngineLayer(void)
{
    IEngineLayer* pInterface = new CEngineLayer;

    return std::shared_ptr<IEngineLayer>(pInterface);
}

In this case the shared_ptr deletes an IEngineLayer and not CEngineLayer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜