尝试删除对象时崩溃

时间:2015-09-20 14:01:43

标签: c++ pointers exception

尝试删除创建的对象时,我的程序崩溃了。认为删除使用关键字new创建的对象是安全的。

为什么会这样?

以下是代码:

标题

#include <iostream>
#include <vector>
#include<string>

template<typename T>
class Postgre {
public:
    Postgre();

    std::vector<T*> get_user();
    std::vector<T*> get_fake_user();

    ~Postgre();
};

class User {
public:
    User(short id, std::string first_name, std::string last_name) {
        this->ID = id;
        this->first_name = first_name;
        this->last_name = last_name;
    }

    short ID;
    std::string first_name;
    std::string last_name;
};

class Fake_User {
public:
    Fake_User(short id, std::string user_name, std::string user_pw) {
        this->ID = id;
        this->user_name = user_name;
        this->user_pw = user_pw;
    }

    short ID;
    std::string user_name;
    std::string user_pw;
};

来源

template<typename T>
Postgre<T>::Postgre() {

}

template<typename T>
Postgre<T>::~Postgre() {
}

template<typename T>
std::vector<T*> Postgre<T>::get_user() {
    T* user = new T(1, "Peter", "Peters");
    std::vector<T*> result;

    result.push_back(user);
    delete user;
    return result;
}

template<typename T>
std::vector<T*> Postgre<T>::get_fake_user() {
    T* fake_user = new T(2, "Beverly", "Peters");
    std::vector<T*> result;

    result.push_back(fake_user);
    delete fake_user;
    return result;
}

template class Postgre<User>;
template class Postgre<Fake_User>;

主要

int _tmain(int argc, _TCHAR* argv[]){
   Postgre<User>* postgre = new Postgre<User>();

   //test User Class:
   std::vector<std::vector<User*>> list_user;
   list_user.push_back(postgre->get_user());

    std::cout << list_user[0][0]->ID << std::endl;
    std::cout << list_user[0][0]->first_name << std::endl;
    std::cout << list_user[0][0]->last_name << std::endl;

    std::cout << std::endl;
    //test Fake_User Class:
    Postgre<Fake_User>* postgre2 = new Postgre<Fake_User>();

    std::vector<std::vector<Fake_User*>> list_fake_user;
    list_fake_user.push_back(postgre2->get_fake_user());

    std::cout << list_fake_user[0][0]->ID << std::endl;
    std::cout << list_fake_user[0][0]->user_name << std::endl;
    std::cout << list_fake_user[0][0]->user_pw << std::endl;

    //wait for keypress
    std::cin.ignore();

    return 0;
}

0 个答案:

没有答案