c++ - 当我从常量引用调用方法时程序失败

标签 c++

所以,我有一个 token 类: token .h

class Token {
    std::string name; // token name
    int frequency;//frequency
    Vector lines;//lines where the token is present

public:
    //explanations for the methods in the Token.cpp
    Token(std::string tokenname, int linenumber);
    virtual ~Token();
    const Vector getLines() const;
};
#endif /* TOKEN_H_ */

token cpp

Token::Token(string tokenname, int linenumber) {
    // TODO Auto-generated constructor stub
    name = tokenname;
    frequency=1;
    lines.push_back(linenumber);
}
Token::~Token() {
    // TODO Auto-generated destructor stub
}
std::string Token::getName() const{
    return name;
}
int Token::getFrequency() const{
    return frequency;
}
const Vector Token::getLines() const{
    const Vector vec = lines;
    return lines;
}

程序失败,当我将它传递给列表类的插入方法时

class List {
private:
    class Node {
    public:
        Token data;
        Node* next;
        Node(const Token &dataItem, Node* nextptr);
        ~Node();

    };
    Node* first;
    int length;
public:
    List();
    virtual ~List();
    void insert(const Token &t);
};

列表.cpp:

List::Node::Node(const Token &dataItem, Node* nextptr): data(dataItem), next(nextptr){
}
List::Node::~Node(){
cout<<"dead"<<endl;
}

List::List() {
    // TODO Auto-generated constructor stub
    length = 0;
    first = nullptr;
}

List::~List() {
    // TODO Auto-generated destructor stub
    Node* temp = first;
    Node* newtmp;
               while(temp->next != nullptr){
                   newtmp = temp->next;
                   delete temp;
                   temp = newtmp;
               }
}
const int List::size(){
    return length;
}

void List::insert (const Token &t){

        Vector dammit = t.getLines();

}

我发现插入的是哪一行(Vector dammit = t.getLines()),所以我就这样保留了。 它给了我这个错误信息:

double free or corruption (fasttop): 0x0000000000c34040 ***

如果你想运行,这里是主文件中的一些内容:

int main() {
//  cout<<"tokens are here"<<endl;
//
    Token hit("aca", 1);
    Token hit2("ui", 2);
    Token hit1("111", 3);
    List list;
    list.insert(hit);
    list.insert(hit2);
    list.insert(hit1);
}

vector 类:

class Vector {

int* store;
int capacity;
int next_index;
public:
    Vector();
    Vector(int initial_size);
    Vector(const Vector &v);
    virtual ~Vector();
    void push_back(int item);
    int pop_back();
    const int size() const;
    void resize();
    void operator =(const Vector &v);
    int& operator[] (int k);
    const int& operator[] (int k) const;
    friend std::ostream& operator<<(std::ostream& os, const Vector& v);

};
Vector::Vector() {
    // TODO Auto-generated constructor stub
    store = new int [1];
    capacity = 1;
    next_index = 0;
}

Vector::Vector(int initial_size){
    store = new int [initial_size];
    capacity = initial_size;
    next_index = 0;
}

Vector::Vector(const Vector &v){
    store = v.store;
    capacity = v.capacity;
    next_index = v.next_index;
}

Vector::~Vector() {
    // TODO Auto-generated destructor stub
    delete[] store;
}
void Vector::resize(){
    std::cout<<"in resize"<<std::endl;
std::cout<<capacity<<std::endl;
    int length = capacity;
    capacity+=100;
    int* tempArray;
    tempArray = new int[capacity];
    for (int i=0; i<length; i++){
        tempArray[i] = store[i];
    }
    if (length>1)
    delete[] store;
    std::cout<<"finish re4size"<<std::endl;
    store = tempArray;


}

void Vector::push_back(int item){
    if(next_index >= capacity)
        this->resize();
    store[next_index] =item;
    next_index++;
}

int Vector::pop_back(){
    next_index = next_index-1;
    int last = store[next_index];
    return last;
}

void Vector::operator =(const Vector &v){
    //delete[] store;
    store = v.store;
    capacity = v.capacity;
    next_index = v.next_index;
}
const int Vector::size() const{
    return next_index-1;
}
int& Vector::operator[] (int k){
    //assert((k<next_index)&(k>=0));
    return store[k];
}
const int& Vector::operator[] (int k) const{
    //assert((k<next_index)&(k>=0));
    return store[k];
}
ostream& operator<<(ostream& os, const Vector& v)
{
    for(int i=0; i<=v.size(); i++){
       os <<  v[i]<< ' ';
    }
    return os;
}

最佳答案

Vector::Vector(const Vector &v){
    store = v.store;
    capacity = v.capacity;
    next_index = v.next_index;
}

您现在有两个 vector 指向同一个 int* store;

void Vector::operator =(const Vector &v){
    //delete[] store;
    store = v.store;
    capacity = v.capacity;
    next_index = v.next_index;
}

你做同样的事情。

当你打电话时

const Vector Token::getLines() const{
    const Vector vec = lines;
    return lines;
}

vec = lines 使用复制构造函数。您现在有 vec 和 lines 指向同一家商店。

您返回行的拷贝,这将再次触发复制构造函数。第三个对象现在指向存储。

当堆栈展开时,本地定义的 vec 被销毁。 ~Vector 删除的商店。您现在有两个对象指向同一个取消分配的存储区。

轰隆隆!一旦您尝试使用这些 vector 中的任何一个做很多其他事情。看起来返回的 Vector 的破坏首先命中并导致析构函数重新删除存储。

您需要为新存储分配存储空间,然后在 = 运算符和复制构造函数中将源存储的内容复制到新存储中。

Vector::Vector(const Vector &v){
    capacity = v.capacity;
    store=new int[capacity];
    for (size_t index; index < capacity; index++)
    {
        store[index] = v.store[index];
    }
    next_index = v.next_index;
}

Vector & Vector::operator =(const Vector &v){
    delete[] store;
    capacity = v.capacity;
    store=new int[capacity];
    for (size_t index; index < capacity; index++)
    {
        store[index] = v.store[index];
    }
    next_index = v.next_index;
}

std::copy 可用于代替 C++11 中的 for 循环。也可以使用古老的 memcpy,但这只是因为 store 是原始数据类型。

在我编辑的时候,感谢 Jarod42,还有一个小调整:

const Vector & Token::getLines() const{ //note the return of a reference. This avoids 
                                        // making a copy of lines unless the caller really 
                                        // wants a copy.
    // const Vector vec = lines; don't need to do this. lines is const-ified by the
    // const on the return type of the function
    return lines;
}

关于c++ - 当我从常量引用调用方法时程序失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30746675/

相关文章:

c++ - qmake:如何去除绝对路径的依赖?

GNU automake 中的 C++11 支持

c++ - OpenCV GTK+2.x 错误 - "Unspecified error (The function is not implemented...)"

c++ - child 的构造函数无法识别基类的成员 : mean, sigma "is not a nonstatic data member or base class"

引用的 C++ 复制省略

c++ - 未在此范围内声明的对象构造函数调用

c++ - 使用定义的类在 C++ 中排序

python - 如何在工作线程中使用关闭句柄

c++ - 错误 : ‘split’ was not declared in this scope

c++ - 没有 edge_predicate 的 BOOST filtered_graph 中的 out_edges() 实现