传递带有派生类的unique_ptr导致SEGFAULT。

huangapple go评论70阅读模式
英文:

Passing unique_ptr with derived class causes SEGFAULT

问题

当我将D类中的unique_ptr对象更改为包含B类对象而不是A类对象时,为什么在这里执行函数foo()会导致SEGFAULT?```class A
{
public:
virtual void function() = 0;
};

class B : public A
{
public:
void function()
{
std::cout << "works!!";
}
};

class D
{
public:
D(const std::unique_ptr& arg): object(arg) {}

void foo()
{
    object->function();
}

private:
const std::unique_ptr<A>& object;

};

int main()
{
std::unique_ptr object = std::make_unique();
D d(std::move(object));

d.foo();

}```我很好奇背后的逻辑是什么。

英文:

could someone explain to me why executing function foo() here causes SEGFAULT? When I change the unique_ptr object in D class to contain B class object instead of A, everything works ok.

class A
{
    public:
    virtual void function() = 0;
};

class B : public A
{
    public:
    void function()
    {
        std::cout &lt;&lt; &quot;works!!&quot;;
    }
};

class D
{
    public:
    D(const std::unique_ptr&lt;A&gt;&amp; arg): object(arg) {}

    void foo()
    {
        object-&gt;function();
    }

    private:
    const std::unique_ptr&lt;A&gt;&amp; object;
};


int main()
{
    std::unique_ptr&lt;B&gt; object = std::make_unique&lt;B&gt;();
    D d(std::move(object));

    d.foo();
}

I'm curious what's the logic behind it.

答案1

得分: 6

你将一个引用传递给智能指针对象。这个智能指针对象将在d对象创建后立即销毁。这会导致你拥有一个无效的引用。当你尝试使用它时,将出现未定义的行为

而是通过传递指针对象,在对象中按值存储它,并移动它到对象中:

class D
{
public:
    D(std::unique_ptr&lt;A&gt; arg): object(std::move(arg)) {}

    // ...

    std::unique_ptr&lt;A&gt; object;
};
英文:

You pass a reference to the smart pointer object. This smart pointer object will be destructed as soon ad the d object have been created. That leaves you with an invalid reference. When you try to use it, you will have undefined behavior.

Instead pass the pointer object by value, store it by value in the object, and move it into the object:

class D
{
public:
    D(std::unique_ptr&lt;A&gt; arg): object(std::move(arg)) {}

    // ...

    std::unique_ptr&lt;A&gt; object;
};


</details>



huangapple
  • 本文由 发表于 2023年8月4日 22:57:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定