c++ostringstream对象在返回main函数后导致未处理的异常


Unhandled exception at 0x53e83d80 in TestGame.exe: 0xC0000005: Access violation reading         
location 0xfeeefef6.

当我关闭SFML窗口时,我的C++程序抛出一个未处理的异常(导致主类返回0;

导致此问题的代码是一个std::ostringstream对象,如果我不使用它,问题就不会发生。。

void Orbs::UpdateText()
{
oss.str("");
oss << air_orbs.number;
air_orbs.text.setString(oss.str());
oss.str("");
oss.flush();
}

类标题:

#pragma once
#include <SFML/Graphics.hpp>
#include "FieldConst.h"
#include <sstream>
int const ORB_CHAR_SIZE = 20;
float const ORB_SCALE_SIZE = 0.25f;
struct  Orb
{
sf::Texture texture;
sf::Sprite sprite;
int number;
sf::Text text;
void Add(){
    number++;
}
void Remove(){
    number--;
}
};
class Orbs
{
public:
Orbs();
~Orbs();
void Render(sf::RenderWindow &target);
void UpdateText();
private:
Orb air_orbs, darkness_orbs, death_orbs, earth_orbs, electricity_orbs,
    fire_orbs, life_orbs, light_orbs, machine_orbs, metal_orbs, time_orbs,     water_orbs;
std::ostringstream oss;
};

Player::Player()
{
Player::name = "Player1";
Player::deck = new Deck();
Player::voidZone = new Deck();
Player::hand = new Hand();
Player::orbs = new Orbs();
}

#pragma once

#include "IncludeCards.h"
#include "Orbs.h"
class Player
{
 public:
Player();
~Player();
std::string GetName();
Deck* GetDeck();
Hand* GetHand();
Deck* GetVoidZone();
Orbs* GetOrbs();

void DrawFromDeck();
void DiscardToVoid(Card *cardToDiscard);
//void UseCard ability/invoke/spell
private:
std::string name;
Deck *deck;
Hand *hand;
Deck *voidZone;
Orbs *orbs;
};

我能做些什么来修复它?提前感谢

我不明白你为什么要让oss成为Orbs的成员。它的使用方式更适合局部变量,因此您应该删除它:

class Orbs
{
public:
Orbs();
~Orbs();
void Render(sf::RenderWindow &target);
void UpdateText();
private:
Orb air_orbs, darkness_orbs, death_orbs, earth_orbs, electricity_orbs,
    fire_orbs, life_orbs, light_orbs, machine_orbs, metal_orbs, time_orbs,     water_orbs;
};
void Orbs::UpdateText()
{
    std::stringstream oss;
    oss << air_orbs.number;
    air_orbs.text.setString(oss.str());
}

或者使用C++11:

void Orbs::UpdateText()
{
    air_orbs.text.setString(std::to_string(air_orbs.number));
}

相关内容

最新更新