c ++ return element在没有代码的情况下在线提供访问冲突

时间:2014-10-29 14:16:49

标签: c++ class access-violation

当我尝试从我的数组中返回一个元素时,我的程序崩溃并且它在visual studio 2012中显示访问冲突。我不知道这是怎么可能的,因为我初始化了数组并为它分配了内存。我有一个类Tweet,我初始化推文。我还有一个类索引元素,它将推文与数组中的相同主题标签放在一起。 索引元素的标题:

#ifndef INDEXELEMENT_H
#define INDEXELEMENT_H
#include "Tweet.h"
#include <string>

class IndexElement {
private:
    std::string hashtag;
    int size;
    Tweet* array;
    int memory;
public:
    IndexElement(std::string tag);
    IndexElement(const IndexElement& copy);
// Default constructor om makkelijker te kunnen werken in de klasse HashTagIndexer.
    IndexElement();
    ~IndexElement();
public:
    std::string getHashTag() const;
    void addTweet(Tweet tweet);
    int getNumTweets() const;
    Tweet getTweet(int i) const;
};
#endif

推文标题:

#ifndef TWEET_H
#define TWEET_H
#include <string>
class Tweet{
private:
    int id;
    std::string tweeter;
    time_t date;
    std::string tweet;
    std::string* tags;
    int num_tags;
public:
    Tweet(int id, std::string tweeter, time_t date, std::string tweet, std::string* tags, int     num_tags);
    Tweet();
    ~Tweet();
public:
    int getID() const;
    std::string getTweeter() const;
    time_t getDate() const;
    std::string getTweet() const;
    int getNumHashtags() const;
    std::string getHashtag(int i) const;
};
#endif

我做了一些测试,但是在这个测试中它给了我一个错误:

bool addTweetIndexElementTest()
{
    IndexElement a("#test");
    string tags[1] = {"#test"};
    Tweet t1(1,"lennart",0,"dit is een teststring",tags,1);
    a.addTweet(t1);
    cout << a.getTweet(0).getID(); // program crashes here!!

}

getTweet实现:

Tweet IndexElement::getTweet(int i) const{
    if(i>=size){
        return Tweet();
    } else {
        cout << array[i].getID();  
        return array[i];  // this actually works (i.e. it don't crashes on this line)
    }
}  // when I set a breakpoint on this line en press continue the program crashes. Don't know why because there's no code and the program also doesn't go to the destructor so it also couldn't be that.

可以肯定的是,这是我的析构函数:

IndexElement::~IndexElement(){
    delete[] array;
}

Tweet::~Tweet(){
    delete[] tags;
}

我做错了什么,但我不知道是什么。

1 个答案:

答案 0 :(得分:0)

您的参数是值传递,它是堆栈上的本地副本:

void addTweet(Tweet tweet); // tweet will be freed when leaving the function

请改为:

void addTweet(const Tweet& tweet); // assumes there is a copy constructor for Tweet
void addTweet(Tweet* tweet);       // will not retain the Tweet object

除非你这样做是练习,否则我强烈建议你使用std :: vector而不是你的列表的原始指针。

相关问题