Search code examples
c++c++11vectorabstract-classerase

C++ vector erase method delete my object


I first get an object A from the vector, then I call the erase method to destroy that object in my vector because I don't need it anymore. However, from the debugger, I found that the object A I got before calling erase method is also destroyed. I don't understand that because I thought that what I got is a copy of that object and erase method should have nothing to do with my object A.

Code

Class Unit

Header file

#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 file

#include "Unit.h"

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

int Unit::getID()
{
    return id;

}

Class Box

Header file

#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 file

#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;
}

main file

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;
}

Below is the screenshot from the debugger and because I don't have 10 reputations, I can't display it directly.

before

after

As you can see, the "type" and "val" data member of class Box is modified.


Solution

  • Check out this page about the return type from the index call

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

    I believe that you may have a reference, not a different object.