简体   繁体   English

调用函数时,c ++无法使用自定义类读取内存

[英]c++ unable to read memory with custom class when calling a function

I am having problems running functions within a custom class. 我在自定义类中运行函数时遇到问题。 Here is my code: 这是我的代码:

ROBOTSTRUCTURE.H 机器人结构

#pragma once

#include "math.h"
#include <fstream>
#include <string>
#include <thread>
#include <chrono>
#include <ctime>
#include <vector>
#include <sstream>
#include <fstream>

using namespace std;
using namespace std::chrono;
class RobotStructure
{
    bool faceTrackingEnabled;

public:
    RobotStructure();
    ~RobotStructure();
    bool testFunction(string input);

ROBOTSTRUCTURE.CPP 机器人结构

#include "RobotStructure.h"
RobotStructure::RobotStructure()
{
    faceTrackingEnabled = true;
}

RobotStructure::~RobotStructure()
{
}

bool RobotStructure::testFunction(string input)
{
    cout << input << endl; //THIS DOES NOT WORK, When using debugger shows that the entire class "Robot Structure" as unable to read memory
return true;
}

MAIN 主要

#include <Windows.h>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
#include <thread>
#include <string>
#include <sstream>
#include <vector>
#include <math.h>
#include <fstream>

#include "RobotStructure.h"
using namespace std;
int main()
{
    RobotStructure *mybot= new RobotStructure();
    mybot->testFunction("test");
    return 0;
}

If a set a breakpoint in main, my class is initialized correctly and everything is fine. 如果在main中设置了断点,则我的类将正确初始化,并且一切都很好。 As soon as a call the "test function" the class falls out of memory within the test function. 一旦调用“测试功能”,该类就会从测试功能内的内存中丢失。

When it goes back to main just before return 0; 当返回main之前,返回0;否则,返回0。 the class is also out of memory. 该类也内存不足。 As if the pointer is deleted somehow. 好像指针以某种方式被删除。 Can someone please explain what is happening and what did I do that is wrong? 有人可以解释发生了什么,我做错了什么?

You declared the function as bool testFunction(string input) but the function is not returning anything. 您将该函数声明为bool testFunction(string input)但该函数未返回任何内容。 This leads to undefined behavior in C++. 这导致C ++中的未定义行为。

In addition your example wouldn't compile (you declared an argument input but you are using intput ). 另外,您的示例无法编译(您声明了参数input但您正在使用intput )。

Your testFunction does not use any class members. 您的testFunction不使用任何类成员。 If you compile this code with optimization enabled ("Release"-Configuration in VisualStudio, -O2 on gcc), the compiler might render some variables (like this ) "undebuggable". 如果您编译此代码启用优化(在VisualStudio中“释放” -构型-O2海合会),编译器可能会导致某些变量(如this )“undebuggable”。

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

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