c++ 指针丢失指针引用

标签 c++ pointers runtime-error

我得到了下面描述的类

class Investment
{
private:
    void init(BWAPI::UnitType type1, BWAPI::UpgradeType type2, BWAPI::TechType type3, int numOfItems);
    UpgradeType upgradeType;
    TechType techType;
    UnitType unitType;

我的初始化方法就是这样

void Investment::init(BWAPI::UnitType type1, BWAPI::UpgradeType type2, BWAPI::TechType type3, int numOfItems)
{
    if (type1 != NULL) {

        this->unitType = type1;
        this->type = type1.isBuilding() ? BUILDING_TYPE : UNIT_TYPE;

    } else if (type2 != NULL) {

        this->upgradeType = type2;  
        this->type = UPGRADE_TYPE;

    } else if (type3 != NULL) {

        this->techType = type3; 
        this->type = TECH_TYPE;
    }

    this->numOfItems = numOfItems;
}

然后我通过这种方式得到了我的元素(只能是三种可能类型中的一种)

const void* Investment::getItem() const
{
    if (unitType != NULL)
        return &unitType;
    else if (upgradeType != NULL)
        return &upgradeType;
    else if (techType != NULL)
        return &techType;

    return NULL;
}

但是当我使用 UnitType* type = (UnitType*) investment->getItem(); 指针失去它的值时会发生什么

当我调用 type->getName().c_str(); 时,它返回一个空字符串

为了获得投资,我调用了 Stack 的方法

// I have a stack of type std::vector<T*> stack;

T* getNext() {

    clear();

    for (int i = 0, leni = stack.size(); i < leni; i++) {

        T* t = stack.at(i);

        if (!t->isDone() && !t->isCanceled())
            return t;
    }

    return NULL;
}

最佳答案

我认为您可以通过让 Investment 类持有一个(最好是 smart )指向 Type 基类的指针来大大简化问题。在此示例中,我使用了一个在 Investment 析构函数中被删除的原始指针,但您可能应该使用 std::unique_ptr , 一个 boost::scoped_ptr ,或 std::shared_ptr如果您想将类型的生命周期与 Investment 分离。

class InvestmentType { // some public virtual methods };

class UpdgadeType : public InvestmentType { /* Implement InvestmentType methods*/ };
class TechType : public InvestmentType { /* Implement InvestmentType methods*/ };
class UnitType : public InvestmentType { /* Implement InvestmentType methods*/ };

class Investment
{
 private:
    void init(const InvestmentType&  type, int numOfItems) : nItems_(numOfItems), type_(new type) {}
    int nItems_;
    InvestmentType* type_;
    ~Investment() { delete type_; }
 public:
    const InvestmentType* getItem() const { return type_; }
};

关于c++ 指针丢失指针引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13814577/

相关文章:

c++ - 如何使用 OpenCV 进行人脸识别?

c++ - 使用文件内容作为硬编码字符串

python - 使用 cython 将 c++ 函数暴露给 python

c++ - 我应该删除函数中的局部指针吗? (C++)

c - 函数调用期间的内存管理

c++ - 定义放置 C 字符串的位置

c++ - 从动态数组中删除一个动态对象

android - 如何使用 sqlite 查询从三个表中检索我需要的数据?

ios - 将枚举分配给 Objective-C 中的变量

python运行时警告调试