为什么多态类型错误和清理问题? [英] why the polymorphic types error and cleanup question?

查看:194
本文介绍了为什么多态类型错误和清理问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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'不是多态型。应该做什么来解决这个问题?

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?

推荐答案

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:

class Base {
public:
  virtual ~Base() { }
};






关于您的清理问题:

从技术上讲,这两种方式都有一些未定义的行为,因为映射引用的对象在指针从映射中删除之前就被销毁。这导致映射在被破坏时包含无效指针,并导致未定义的行为。

出于实际目的,这不会对任何已知的编译器造成任何问题。


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.

否则,你正在清理一切。

但是在way2,你可以做一个简化。当 Base 有一个虚拟析构函数时,可以执行

Otherwise, you are properly cleaning up everything.
But in way2, you can make a simplification. When Base has a virtual destructor, you can just do

delete b.find("abc")->second;

这篇关于为什么多态类型错误和清理问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆