C++向量擦除方法删除我的对象

C++ vector erase method delete my object

我首先从向量中获取一个对象 A,然后调用擦除方法销毁向量中的该对象,因为我不再需要它了。但是从调试器中发现调用erase方法之前得到的对象A也被销毁了。我不明白,因为我认为我得到的是那个对象的副本,擦除方法应该与我的对象 A 无关。

代码

Class单位

头文件

#ifndef UNIT_H
#define UNIT_H
#include <iostream>

class Unit
{
protected:
    int id;

public:
    Unit::Unit(int num = -1);
    virtual ~Unit() = default;
    virtual int getID();

};

#endif

CPP 文件

#include "Unit.h"

Unit::Unit(int num)
{
    id = num;
}

int Unit::getID()
{
    return id;

}

Class 盒子

头文件

#ifndef BOX_H
#define BOX_H
#include <string>
#include <iostream>
#include "Unit.h"

class Box : public Unit
{
private:
    std::string* type;
    int* val;
public:
    Box::Box();
    ~Box();
    int getVal();
    std::string getName();
    int getID() override;
};

    #endif

CPP 文件

#include <time.h>
#include "Box.h"

Box::Box() : Unit(5)
{
    int tmp = rand() % 3;
    if (tmp == 0)
    {
        type = new std::string("hp");  // health cur
        val = new int(rand() % 10 + 1);
    }
    else if (tmp == 1)
    {
        type = new std::string("exp");  // skill level or health max
        val = new int(rand() % 5 + 1);
    }
    else
    {
        type = new std::string("punish");  // minus health cur
        val = new int(-1);
    }
}

Box::~Box()
{
    delete type;
    delete val;
}

int Box::getVal()
{
    return *val;
}

std::string Box::getName()
{
    return *type;
}

int Box::getID()
{
    return id;
}

主文件

using namespace std;
int main()
{
    Box test;
    std::vector<Box> bag;
    bag.push_back(test);

    Box tmp = bag[0];

    bag.erase(bag.begin() + 0);

    cout << tmp.getVal();

    system("pause");
    return 0;
}

下面是调试器的截图,因为我没有10个声望,所以不能直接显示。

before

after

如您所见,class Box 的 "type" 和 "val" 数据成员已修改。

查看此页面,了解索引调用中的 return 类型

http://en.cppreference.com/w/cpp/container/vector/operator_at

我相信你可能有一个参考,而不是一个不同的对象。