简体   繁体   English

验证多态向量元素的具体类型是相同的

[英]Veryfing that concrete types of polymorphic vector elements are the same

I have got a abstract base class Type which has multiple concrete child classes like Type_bool , Type_int , Type_double etc. Furthermore I construct two vectors of type std::vector<Type*> holding objects of the concrete child classes.我有一个抽象基础 class Type ,它有多个具体子类,如Type_boolType_intType_double等。此外,我构造了两个std::vector<Type*>的向量,其中包含具体子类的对象。

I have implemented the following method to check whether these vectors are the same.我已经实现了以下方法来检查这些向量是否相同。 In this context same means that they are of the same size and that for all elements in the vectors it holds that type(v1[i]) == type(v2[i]) for all i=1,2, ... v1.size .在这种情况下,相同意味着它们具有相同的大小,并且对于向量中的所有元素,它对所有i=1,2, ... v1.size都持有type(v1[i]) == type(v2[i]) i=1,2, ... v1.size .大小。

bool Env::areArgsTheSame(std::vector<Type*> containedFunArgs, std::vector<Type*> otherFunArgs)
{
    if(containedFunArgs.size() != otherFunArgs.size())
        return false;

    bool argsSame = true;
    for(std::size_t index = 0; index < containedFunArgs.size(); index++) {
        auto *arg = containedFunArgs[index];
        auto *otherArg = otherFunArgs[index];

        if(typeid(*arg) != typeid(*otherArg)){
            argsSame = false;
            break;
        }
    }

    return argsSame;
}

The problem is that whenever I call the function with these to vectors I get a segmentation fault.问题是,每当我用这些向量调用 function 时,我都会遇到分段错误。 I've been trying to fix this issue for ages now and can't seem to find a way.我已经尝试解决这个问题很久了,但似乎找不到办法。 Any help is appreciated.任何帮助表示赞赏。

Edit: I was able to narrow down the error to dereferencing in the for loop.编辑:我能够将错误缩小到在 for 循环中取消引用。 But I don't know any other way to access the concrete types.但我不知道访问具体类型的任何其他方式。

Edit2: I create containedFunArgs and otherFunArgs in this manner: Edit2:我以这种方式创建otherFunArgs containedFunArgs

     Type_int *a, *b;
     Type_bool* c;

     std::vector<Type*> arguments = {a, b};
     std::vector<Type*> arguments2 = {a, c};

Consider the code...考虑代码...

Type_int *a, *b;
Type_bool* c;

std::vector<Type*> arguments = {a, b};
std::vector<Type*> arguments2 = {a, c};

The pointers a , b , and c are uninitialized.指针abc未初始化。 So when you dereference them in Env::areArgsTheSame you invoke undefined behaviour which (in this case at least) results in a seg fault.因此,当您在Env::areArgsTheSame中取消引用它们时,您会调用未定义的行为,这(至少在这种情况下)会导致段错误。

Your pointers need to point to valid instances of their associated types.您的指针需要指向其关联类型的有效实例。 So you might, for example, do...因此,例如,您可能会...

Type_int a, b;
Type_bool c;

std::vector<Type*> arguments = {&a, &b};
std::vector<Type*> arguments2 = {&a, &c};

and then pass arguments and arguments2 to Env::areArgsTheSame .然后将argumentsarguments2传递给Env::areArgsTheSame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM