为什么会出现多态类型错误和清理问题?
#include <iostream>
#include <string>
#include <map>
#include <vector>
class base {};
class derived1 : public base
{
public:
unsigned short n;
derived1()
{
n = 2;
}
};
class derived2 : public base {};
void main()
{
// way 1
{
std::vector<derived1> a1;
std::vector<derived2> a2;
std::map<std::string, base*> b;
a1.push_back(derived1());
b["abc"] = &a1.at(0);
std::cout<<(dynamic_cast<derived1*>(b.find("abc")->second))->n<<std::endl;
}
// way 2
{
std::map<std::string, base*> b;
b["abc"] = new derived1();
std::cout<<dynamic_cast<derived1*>(b.find("abc")->second)->n<<std::endl;
delete dynamic_cast<derived1*>(b.find("abc")->second);
}
}
错误是“'dynamic_cast':'base'不是多态类型”。应该采取什么措施来解决这个问题?方式 1 和方式 2 中的所有内容都已正确清理吗?
#include <iostream>
#include <string>
#include <map>
#include <vector>
class base {};
class derived1 : public base
{
public:
unsigned short n;
derived1()
{
n = 2;
}
};
class derived2 : public base {};
void main()
{
// way 1
{
std::vector<derived1> a1;
std::vector<derived2> a2;
std::map<std::string, base*> b;
a1.push_back(derived1());
b["abc"] = &a1.at(0);
std::cout<<(dynamic_cast<derived1*>(b.find("abc")->second))->n<<std::endl;
}
// way 2
{
std::map<std::string, base*> b;
b["abc"] = new derived1();
std::cout<<dynamic_cast<derived1*>(b.find("abc")->second)->n<<std::endl;
delete dynamic_cast<derived1*>(b.find("abc")->second);
}
}
The error is "'dynamic_cast' : 'base' is not a polymorphic type". What should be done to fix this? Is everything properly cleaned up in both way1 and way2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使
Base
成为多态类型,您需要为其提供至少一个虚函数。在这种情况下最简单的是析构函数:关于您关于清理的问题:
从技术上讲,这两种方式都存在一些未定义的行为,因为在从映射中删除指针之前,映射引用的对象已被销毁。这导致映射在被破坏时包含无效指针并导致未定义的行为。
出于实际目的,这不会对任何已知的编译器造成任何问题。
否则,你就正确地清理了一切。
但在方法2中,你可以进行简化。当
Base
有一个虚拟析构函数时,你可以不用动态转换。
To make
Base
a polymorphic type, you need to give it at least one virtual function. The easiest in this case would be the destructor:Regarding your question about cleanup:
Technically, there is some undefined behaviour in both ways, because the objects that the map refers to are destroyed before the pointers are removed from the map. This has the result that the map, when it is destructed, contains invalid pointers and that causes undefined behaviour.
For practical purposes, this does not cause any problems with any known compiler.
Otherwise, you are properly cleaning up everything.
But in way2, you can make a simplification. When
Base
has a virtual destructor, you can just dowithout the dynamic cast.