【问题标题】:Calling a class which written in file .hpp make error "Exception thrown: read access violation. this->p was nullptr."调用写入文件 .hpp 的类会产生错误“抛出异常:读取访问冲突。this->p was nullptr。”
【发布时间】:2021-11-27 10:32:09
【问题描述】:

我正在文件 .hpp 中编写一个类,我正在使用 VS2019 和 opencv 3.4.1。 它返回此错误:

Exception thrown: read access violation.
this->p was nullptr. at line 1419 of file mat.inl.hpp

当我只编译那个 .hpp 文件时,它成功且没有错误,但是如果我尝试在另一个文件中声明这个类,它会返回这个错误:

Error pic

这就是我的文件 .hpp 的样子

#pragma once
#include "Header_1.h"

class GUI_1
{
private:
    //Create a black image 
    Mat imgBlank = Mat::zeros(original.size(), CV_8UC3);

    //Take size original to 2 part
    int height = original.size().height;
    int width = original.size().width;

public:
    //Sources img (input)
    Mat original;

    //extension coordinate variable for tracking object
    int posX;
    int posY;
    //last line of  input
    
    //color for cross hair and coordinate
    double red = 0;
    double green = 255;
    double blue = 255;


    //function
    Mat crosshair()
    {
        // Crate blank img
        Mat img = imgBlank;

        //properties
        int length = 10;
        
        //draw crosshair
        //horizon
        line(img, Point(posX - length, posY), Point(posX + length, posY), Scalar(blue, green, red), 1);

        //vertical
        line(img, Point(posX, posY - length), Point(posX, posY + length), Scalar(blue, green, red), 1);

        return img;
    }

    Mat imgCoordinate()
    {
        //blank img
        Mat img = imgBlank;

        //coordinate of text with object
        const int subX = 2;
        const int subY =2;

        //put coordinate

        string Text = "X=" + to_string(posX) + "Y=" + to_string(posY);
        putText(img, Text, Point(posX + subX, posY + subY), FONT_HERSHEY_COMPLEX, 1, Scalar(blue, green, red), 1);

        return img;
    }

    //Create imgGUI for show (output)
    Mat imgGUI = imgBlank + crosshair() + imgCoordinate();

};

【问题讨论】:

标签: c++ class opencv


【解决方案1】:

考虑这个有同样问题的代码:

#include <iostream>

struct MatSize {
    int value = 42;
    int operator()(){ return value; }
};

struct Mat {
    MatSize size;
};

struct Foo {
    int x = m.size();
    Mat m;
};

int main(int argc, char* argv[]){
    Foo f;
    std::cout << f.x;
}

Possible output is0。虽然它可以打印任何其他内容,因为代码具有未定义的行为。成员按照它们在类定义中列出的顺序进行初始化。因此,x = m.size(); 从未初始化的MatSize::value 中读取。在调试版本中,当您在尚未初始化的实例上调用 MatSize::operator() 时,可能会有一些安全网产生运行时错误。

注意初始化顺序。没关系:

struct Foo {
    Mat m;
    int x = m.size();
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2016-08-25
    • 2020-09-12
    • 2016-11-11
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多