我试图理解为什么bad_weak_ptr
调用时会出现异常shared_from_this
。
#include <memory>
#include <iostream>
class parent : public std::enable_shared_from_this<parent>
{
public:
void compare(std::shared_ptr<parent> const& p2)
{
std::cout << (this->shared_from_this() == p2->shared_from_this());
}
};
class child1 : public parent
{};
class child2 : public parent
{};
class child3 : public child1, public child2
{};
void compare(parent& p1, parent& p2)
{
std::cout << &p1 << " : " << &p2 << "\n";
std::cout << (&p1 == &p2);
}
void compare(std::shared_ptr<parent> const& p1, std::shared_ptr<parent> const& p2)
{
compare(*p1, *p2);
// p1->compare(p2); // bad_weak_ptr
// auto p = p1->shared_from_this(); // bad_weak_ptr
}
void compareusingchild(std::shared_ptr<child1> const& c1, std::shared_ptr<child2> const& c2)
{
compare(c1, c2);
}
int main()
{
std::shared_ptr<child3> c3 = std::make_shared<child3>();
try
{
compareusingchild(c3, c3);
}
catch (std::exception& e)
{
std::cout << e.what();
}
return 0;
}
我发现通过使class parent
继承虚拟化,这个问题似乎不会持续存在。为什么这不是编译时错误?当找不到正确的继承父级时,类似于“模棱两可的函数调用”?
仅包含父类的 API 无法提前知道继承层次结构,调用 compare 方法(在父类中)将导致运行时错误。是否可以在编译时检测到此类错误?