c++ - 在指向 vector 的智能指针上使用 push_back() 时出现运行时错误

标签 c++ pointers vector runtime-error

我正在尝试通过取消引用智能指针来填充 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/

相关文章:

c++ - 避免预定义数字常量与 C++ 中的枚举冲突

arrays - C程序语法

vector - 操纵两个向量之间的距离

c++ - 从不同的线程调用 Lua 函数可以吗(在 C++ 中嵌入 Lua)?

c++ - Armadillo的cx_mat和Boost的odeint编译报错

c++ - 如何指向引用类的函数?

c++ - vector 增长时如何强制执行 move 语义?

为联合结构编写可存储向量定义时的优化建议

c++ - 确定树的内部路径长度 (C++)

c++ - 指向静态成员变量的指针