簡體   English   中英

工廠方法創建shared_ptr對象

[英]Factory method creating shared_ptr object

當使用工廠創建對象時,例如下面的示例,在某些情況下,由shared_ptr包裝的對象顯然會在返回過程中被刪除(在調試過程中,該對象已創建,但是將其分配給this->xs引發異常)。 當我更改工廠方法以返回原始指針,並且Link::xs成員成為unique_ptr ,代碼運行良好。 shared_ptr到底是什么原因導致它表現出這種行為? 它與shared_ptr<CrossSection>包裝一個Circular對象有關嗎? 測試已使用MS Visual C ++ 2012完成。

class Link
{
private:
    std::shared_ptr<xs::CrossSection> xs;
public:
    void parseXsection(const std::vector<std::string>& parts);
    std::shared_ptr<xs::CrossSection> getXs() { return this->xs; }
};
void Link::parseXsection(const std::vector<std::string>& parts)
{
    this->xs = xs::Factory::create(parts[1]);
}

namespace xs
{
    class CrossSection
    {
    };
    class Circular : public CrossSection
    {
    };
    class Dummy : public CrossSection
    {
    };
    class Factory
    {
    public:
        static std::shared_ptr<CrossSection> create(const std::string& type);
    };
    std::shared_ptr<CrossSection> Factory::create(const std::string& type)
    {
        if (geom == "circular")
        {
            return std::shared_ptr<CrossSection>(new Circular());
        }
        else
        {
            return std::shared_ptr<CrossSection>(new Dummy());
        }
    }
}

因此,馬丁有一個解決析構函數問題的選項。 您可以添加虛擬析構函數。

但是,由於您使用的是std::shared_ptr ,它使用了一些類型的擦除,因此您可以進行較小的修復:

std::shared_ptr<CrossSection> Factory::create(const std::string& type)
{
    if (geom == "circular")
        return std::shared_ptr<Circular>(new Circular());
    else
        return std::shared_ptr<Dummy>(new Dummy());
}

或者,甚至更好:

std::shared_ptr<CrossSection> Factory::create(const std::string& type)
{
    if (geom == "circular")
        return std::make_shared<Circular>();
    else
        return std::make_shared<Dummy>();
}

為了使用多態性,您絕對需要在CrossSection基類中定義一個虛擬析構函數,即,為了聲明派生類並使用它們來代替父類(因此通常幾乎每次您都想使用派生類...)

class CrossSection {
  public:
    virtual ~CrossSection() { /* Nothing to do here ... */ }
};

參見例如何時使用虛擬析構函數? 還是每個類都應該有一個虛擬的析構函數? 有關更多說明。

PS:我現在不能說,如果這是導致您shared_ptr問題的原因,但是它看起來很像是您忘記虛擬析構函數時可能遇到的問題...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM