英文:
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 << "works!!";
}
};
class D
{
public:
D(const std::unique_ptr<A>& arg): object(arg) {}
void foo()
{
object->function();
}
private:
const std::unique_ptr<A>& object;
};
int main()
{
std::unique_ptr<B> object = std::make_unique<B>();
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<A> arg): object(std::move(arg)) {}
// ...
std::unique_ptr<A> 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<A> arg): object(std::move(arg)) {}
// ...
std::unique_ptr<A> object;
};
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论