【发布时间】:2018-06-23 18:30:16
【问题描述】:
我正在复制 C++ Primer 第 5 版中的 TextQuery 示例。代码可以编译,但在执行 push_back 操作时,它会不断从 Vector 标头抛出“读取访问冲突”。这是我的代码(* 是有错误的那一行):
//main.cpp
#include "stdafx.h"
using namespace std;
int main()
{
ifstream ifile;
ifile.open("D:/OneDrive/Learning/C++/ConsoleApplication1/ConsoleApplication1/testfile.txt");
runQueries(ifile); //*
// ...
}
//stdafx.h
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <vector>
#include <string>
#include <memory>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iterator>
#include <sstream>
#include <map>
#include <set>
#include "TextQuery.h"
//TextQuery.h
void runQueries(ifstream &infile)
{
TextQuery tq(infile); //*
// ...
}
class TextQuery {
public:
using line_no = std::vector<std::string>::size_type;
TextQuery(std::ifstream&); //*
// ...
private:
std::shared_ptr<std::vector<std::string>> file;
std::map < std::string, std::shared_ptr<std::set<line_no>>> wm;
};
TextQuery::TextQuery(std::ifstream &is)
{
string text;
while (getline(is, text)) {
file->push_back(text); //*
//...
}
}
下一次执行将在向量头中引发异常:
bool _Has_unused_capacity() const _NOEXCEPT
{ // micro-optimization for capacity() != size()
return (this->_Myend() != this->_Mylast());
}
这是错误信息:
Exception thrown: read access violation.
std::_Vector_alloc<std::_Vec_base_types<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > >::_Myend(...) returned 0xC.
这是我用于测试的文本文件: //文本文件 文字很好 文字很好 文字很好 文字很好 文字很好 文字很好 文字很好 文字很好 文字不错
【问题讨论】:
-
它最初可以工作。但是 TextQuery 没有返回想要的结果。所以我尝试调试它。我不知道我修改了什么,但从那以后这个异常一直发生,即使在我重新启动我的电脑之后也是如此。
-
请提取minimal reproducible example,如果没有它,您的问题将是题外话。特别是,错误发生后的所有代码都可以而且应该被删除。单独的类也是多余的。
-
@UlrichEckhardt 已修改。
-
您忘记分配
file。为什么它是动态分配的? -
@molbdnilo 这解决了我的问题!我从书中复制时错过了一部分:TextQuery::TextQuery(std::ifstream &is):file(new vector
)
标签: c++ visual-studio visual-c++