我试图通过取消引用一个智能指针来填充一个向量.在运行时,程序在用于输入变量的第一个" 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(…)返回的0xC.)在向量文件中,特别是第1793-1795行:
bool _Has_unused_capacity() const _NOEXCEPT
{ // micro-optimization for capacity() != size()
return (this->_Myend() != this->_Mylast());造成这一错误的原因是什么?
发布于 2019-04-18 18:11:15
默认构造的shared_ptr不会指向任何有效的东西。来自ptr
构造一个没有托管对象的shared_ptr,即空
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>>())
{
...
}发布于 2019-04-18 18:11:16
在使用data之前,需要为它分配内存:
Measurement(string pLabel, int pSample_size) {
...
data = std::make_shared<vector<double>>();
...
}发布于 2019-04-18 18:30:07
你从来没有初始化过ptr。下面演示了成员变量的默认初始化器和成员初始化程序列表的使用。
您可以轻松地将ptr初始化添加到初始化列表中,但因为它不依赖于任何构造函数参数。最好以下面的方式声明它的构造,以避免在创建其他构造函数时出现复制/粘贴错误。
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Measurement {
protected:
int sample_size_;
string label_;
shared_ptr<vector<double>> data_{make_shared<vector<double>>()};
public:
// parameterised constructor
Measurement( string pLabel, int pSample_size )
: sample_size_( pSample_size )
, label_( pLabel )
{
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???
}
}
friend ostream& operator<<( ostream& os, Measurement const& op1 )
{
for ( auto& v : *op1.data_ )
os << v << " ";
return os;
}
};
int main()
{
Measurement A( "xData", 5 );
cout << A << endl;
return 0;
} 输出:
g++ example.cpp -o example
Please input your dataset one entry at a time:
1
2
3
4
5
1 2 3 4 5 https://stackoverflow.com/questions/55751553
复制相似问题