c++ - Why am I getting a crash after calling my constructor? I'm trying to push back a shared_ptr to a vector
问题描述
I'm quite new to programming (currently learning C++). I'm trying to learn how to use smart pointers.
I'm trying to do a challenge from a tutorial in which the goal is to fill in data points to a unique_ptr
of a vector that contains shared_ptr
s that points to a data point. When I run it, it shows 0 errors and 0 warnings so I'm a bit lost on what went wrong since it crashes when I start to add the data(int). Would really appreciate some help on what's going on with this code. I'm still confused on using smart pointers.
#include <iostream>
#include <memory>
#include <vector>
class Test {
private:
int data;
public:
Test():data(0) {std::cout<<"\tTest constructor ("<< data << ")"<<std::endl;}
Test(int data): data{data} {std::cout<< "\tTest constructor ("<< data << ")"<<std::endl;}
int get_data() const {return data;}
~Test(){std::cout<<"\tTest destructor ("<<data<<")"<<std::endl;}
};
//Function prototypes
std::unique_ptr<std::vector<std::shared_ptr<Test>>>make();
void fill(std::vector<std::shared_ptr<Test>> &vec, int num);
void display(const std::vector<std::shared_ptr<Test>>&vec);
std::unique_ptr<std::vector<std::shared_ptr<Test>>>make(){
return std::unique_ptr<std::vector<std::shared_ptr<Test>>>();
}
void fill(std::vector<std::shared_ptr<Test>> &vec, int num){
int temp;
for(int i=0; i<num; ++i){
std::cout<<"Enter the data points for ["<<i<<"]:";
std::cin>>temp;
std::shared_ptr<Test>p1 {new Test {temp}};
vec.push_back(p1);
}
}
void display(const std::vector<std::shared_ptr<Test>>&vec){
std::cout<<"--DISPLAYING VECTOR DATA--"<<std::endl;
for(const auto &i:vec)
std::cout<<i->get_data()<<std::endl;
}
int main() {
std::unique_ptr<std::vector<std::shared_ptr<Test>>> vec_ptr;
vec_ptr = make();
int num;
std::cout<<"How many data points do you want to enter: ";
std::cin >> num;
fill(*vec_ptr, num);
display(*vec_ptr);
return 0;
}
解决方案
在函数make
中,return std::unique_ptr<std::vector<std::shared_ptr<Test>>>();
只返回一个什么都没有的空std::unique_ptr
。取消引用和使用它*vec_ptr
会导致未定义的行为。
你可以
return std::unique_ptr<std::vector<std::shared_ptr<Test>>>(new std::vector<std::shared_ptr<Test>>);
或更好
return std::make_unique<std::vector<std::shared_ptr<Test>>>();
推荐阅读
- ruby-on-rails - rails console OR irb 找出当前环境的 RAILS_VERSION
- r - 如何使用 dplyr 根据原始列中的字符将一列变成 3?
- html - RTSP 链接无法在 Google Chrome 中打开
- c++ - QT:QTimeEdit 小部件中“向上”和“向下”箭头的事件
- ios - 如何合并 `iphoneos` 和 `iphonesimulator` 的构建,就像我们过去对使用 `lipo` 的框架所做的那样
- swift - 在 Swift 中监控 Keychain 项目的变化
- android-studio - Android Studio 虚拟设备扩展控件中的位置菜单
- wpf - WPF 绑定到以哈希键为索引的可观察集合
- python - Pandas - 保持组至少有两个不同的代码
- python - 如何在文件和终端之间切换 sys.stdout?