草庐IT

c++ - 添加公共(public)变量时崩溃

coder 2024-02-10 原文

我有一个相当大的 c++ 程序,包括一个类“Character”。在“Character.h”中,首先声明了 CharacterSettings 结构,然后是 Character 类(包括它们的构造函数)。

Character 具有(除其他外)CharacterSettings* 设置和 Point pos。 CharacterSettings 有一个 Point preferredVelocity。

这很好用。

但是,当我将任何公共(public)变量添加到 Character 时,程序会在我调用此命令时崩溃:

drawLine(character.pos, character.pos+character.settings->preferredVelocity, character.radius/3.0, 128, 80, 0);

程序在这一行崩溃:

Point operator + (const Point &p2) const
    { return Point(x + p2.x, y + p2.y); }

我假设它正在尝试执行 character.pos+character.settings->preferredVelocity。我收到的错误信息是

Unhandled exception at 0x004bc4fc in ECMCrowdSimulation.exe: 0xC0000005: Access violation reading location 0x7f80000f.

当我查看它时,p2.x 和 p2.y 是未定义的。没有额外的变量,它们就不是。我完全不知道发生了什么,甚至不知道如何开始调试或者您需要什么信息来帮助我!任何帮助将不胜感激!

编辑:这里至少有 Character.h 文件!

#pragma once

/* 
 * ECM navigation mesh / crowd simulation software
 * (c) Roland Geraerts and Wouter van Toll, Utrecht University.  
 * ---
 * Character: A single moving character in the simulation.
*/

#include "../ECM/GraphComponents/CMNode.h"
#include "VectorOperation.h"
#include "IndicativeRoute.h"
#include "float.h"

#define _USE_MATH_DEFINES
#include <math.h>

#include <vector>
using std::vector;
#include <queue>
using std::queue;

#define CHARACTER_RELAXATIONTIME 0.5f

typedef vector<CMNode>::iterator node_ptr;
class Corridor;
class CMMResult;

    struct CMEdge;
    class CMMInterface;
    class MicroInterface;
    class CMMSceneTransfer;

    struct CharacterSettings
    {
    private:
        bool index_bb_initialized, index_bb_cp_initialized, index_ir_circle_initialized, index_ir_circle_mu_initialized;
        bool index_2nd_ir_circle_initialized, index_2nd_ir_circle_mu_initialized;

    public:
        // --- Unique identifier within the simulation
        int id;

        // --- Velocity and speed
        Point preferredVelocity;// Newly computed velocity *before* local collision avoidance
        Point newVelocity;      // Newly computed velocity (+ collision avoidance), to be applied in the "next" simulation step

        float total_max_speed;  // Maximum possible speed throughout the entire simulation
        float max_speed;        // Maximum speed at this point in time
        float min_desired_speed;// Minimum speed that the character tries to reach when it is not standing still

        Point lastAttractionPoint;

        // --- IRM parameters
        CMMInterface* cmmImplementation; // the type of indicative route to follow within the corridor, e.g. "shortest path" or "weighted side".
        // Only used in WEIGHTED_SIDE:
        float sidePreference;       // bias to following a certain "side" of the corridor. Must be between -1 (left) and 1 (right).
        float sidePreferenceNoise;  // extra noise factor that will be added to sidePreference at each route element.
        // Used in WEIGHTED_SIDE and SHORTEST_PATH
        float preferred_clearance;  // Distance (m) by which the agent prefers to stay away from obstacles.

        // --- Micro simulation model (e.g. for collision avoidance between characters)
        MicroInterface* microImplementation;// the local model to use
        short micro_maxNrNeighbours;        // the number of neighbours to check in the local model
        float micro_personalSpaceRadius;    // radius of the personal space (m), on top of the character's physical radius.
                                            // Entering this disk (radius + personalSpace) is seen as a 'collision'.

        // --- Corridor/Path pointers
        node_ptr index_bb;          // point on backbone path (used for computing attraction force)
        node_ptr index_bb_cp;       // point on the backbone path(used for computing the closest point)
        curve_ptr index_ir_circle;  // index to last point on the indicative route that intersects with a circle
        float index_ir_circle_mu;   // factor wrt to point on the indicative route that intersects with a circle

        friend Character; // only the Character class can look into private members (WvT: ugly C++ practice, but it does work)

        CharacterSettings(int _id, 
            // speed
            float _total_max_speed, float _min_desired_speed,
            // type of indicative route
            CMMInterface* _cmmImplementation, float _sidePreference, float _sidePreferenceNoise, float _clearance, 
            // type of micro simulation model
            MicroInterface* _microImplementation) :

            id(_id), total_max_speed(_total_max_speed), min_desired_speed(_min_desired_speed), 
            cmmImplementation(_cmmImplementation), sidePreference(_sidePreference), sidePreferenceNoise(_sidePreferenceNoise), preferred_clearance(_clearance),
            microImplementation(_microImplementation)
        {
            // velocities
            newVelocity = Point(0, 0);
            max_speed = total_max_speed;
            preferredVelocity = Point(0, 0);

            // corridor/IRM pointers
            index_bb_initialized = false;
            index_bb_cp_initialized = false;
            index_ir_circle_initialized = false;
            index_ir_circle_mu_initialized = false;

            // default micro settings
            micro_maxNrNeighbours = 5; // default for Karamouzas 2010: 5
            micro_personalSpaceRadius = 0.0f; // default for Karamouzas 2010: 0.5
        }
    };

    class Character
    {
    public:
        Point pos;
        float radius;
        Point prevPos;
        int i;    //The thing that is pretending to be the culprit, without this, it works fine.

        // goal data
        Point goalPos;
        float goalRadius;

        // status flags
        bool reachedGoal;
        bool freeze; // whether or not the character is temporarily frozen
        bool freezeNotified;
        bool reachedDestSet;

        Point velocity; // last used velocity

        // corridor/path pointers
        Point retraction, cp;

        //Contains more detailed settings of agent
        CharacterSettings * settings;

    public:
        // --- constructor
        Character(int _id, Point &_pos, float _radius, 
            // speeds
            float _total_max_speed, float _min_desired_speed,
            // type of indicative route
            CMMInterface* _cmmImplementation, float _sidePreference, float _sidePreferenceNoise, float _clearance,
            // type of micro simulation model
            MicroInterface* _microImplementation) :

            pos(_pos), radius(_radius) 
        {
            settings = new CharacterSettings(_id, _total_max_speed, _min_desired_speed, 
                _cmmImplementation, _sidePreference, _sidePreferenceNoise, _clearance, _microImplementation); 

            velocity = Point(0, 0);
            prevPos=_pos;

            reachedGoal = true;
            freeze = false;
            freezeNotified = false;
            reachedDestSet = false;
            //isProxy = false;
        }

        // --- destructor
        void removeSettings();

        // computing the new actual velocity through an acceleration vector: Euler integration
        inline void integrateEuler(const Point &acc, float dtSim)
        {                   
            settings->newVelocity = velocity + dtSim * acc;
            trim(settings->newVelocity, settings->max_speed);
        }

        inline void updatePos(float dtSim) 
        {       
            prevPos=pos;

            // update velocity
            velocity = settings->newVelocity;

            // update position
            pos += dtSim * velocity;

            // if the character is close to its goal, it should stop moving     
            if(!reachedGoal // goal was not already reached
                && settings->lastAttractionPoint == goalPos 
                && distSqr(pos, goalPos) < 0.25)//goalRadius)
            {   
                reachedGoal = true;
                // (do not reset the velocity, so that we can keep the last walking direction)
            }
        }

        void resetIndices();
        node_ptr &getIndex_bb(Corridor &corridor);
        node_ptr &getIndex_bb_cp(Corridor &corridor);
        curve_ptr &getIndex_ir_circle(IndicativeRoute &ir);
        float &getIndex_ir_circle_mu();
        Point &getRetraction() { return retraction; }
        Point &getClosestPoint() { return cp; }

        // computing the cost of some edge (in A*), by using personal preferences
        float getEdgeCost(const CMEdge& edge, float activeFraction);

        // computing the character's area, based on its radius
        float getArea() const;


    };

让一切崩溃的是添加'int i'。

最佳答案

当使用旧版本头文件编译的文件与使用新版本编译的文件之间存在不兼容性时,通常会发生此类奇怪的问题。在这种情况下,两个文件的对象布局可能不同(至少,它的 sizeof 不同)。

因此,在一个文件中,对象可能看起来一切都是正确的,但一旦传递给另一个文件中的函数,您就会得到完全随机的行为。

在这种情况下,重建整个项目可以解决问题。更好的是,如果您手动编写 Makefile,请尝试修复依赖关系。如果您使用的是 gcc/g++,则可以使用这样的命令来生成 Makefile 可接受的依赖项:

g++ -MM -MG -Ipath/to/includes/that/should/be/part/of/dependency *.cpp

关于c++ - 添加公共(public)变量时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11739637/

有关c++ - 添加公共(public)变量时崩溃的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  3. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  4. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  5. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  6. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  7. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  8. Ruby Readline 在向上箭头上使控制台崩溃 - 2

    当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby​​安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少

  9. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  10. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

随机推荐