我正在尝试通过取消引用智能指针来填充 vector 。在运行时,程序在用于输入变量输入的第一个“for”循环的一次迭代后崩溃。
using namespace std;
class Measurement
{
protected:
int sample_size;
string label;
shared_ptr <vector<double>> data;
public:
// parameterised constructor
Measurement(string pLabel, int pSample_size)
{
label = pLabel;
sample_size = pSample_size;
cout << "Please input your dataset one entry at a time:" << endl;
for (int i = 0; i < sample_size; i++)
{
double input;
cin >> input;
data->push_back(input); // NOT WORKING???
}
}
};
int main()
{
Measurement A("xData", 5);
return 0;
}
当使用 VS 调试器时,它显示抛出异常(抛出的异常:读取访问冲突。 std::_Vector_alloc >>::_Myend(...) 在 vector 文件中返回 0xC.),特别是第 1793 - 1795 行:
bool _Has_unused_capacity() const _NOEXCEPT
{ // micro-optimization for capacity() != size()
return (this->_Myend() != this->_Mylast());
这个错误的原因是什么?
最佳答案
默认构造的 shared_ptr
没有指向任何有效的东西。来自 https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr :
Constructs a shared_ptr with no managed object, i.e. empty
shared_ptr
.
您需要对其进行初始化,使其指向其管理的有效对象,然后才能使用底层指针。例如,将构造函数更改为:
Measurement(string pLabel, int pSample_size) : data(new std::vector<double>())
{
...
}
或
Measurement(string pLabel, int pSample_size) : data(std::make_shared<std::vector<double>>())
{
...
}
关于c++ - 在指向 vector 的智能指针上使用 push_back() 时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55751553/