![](/img/trans.png)
[英]Why I am able to assign constant shared_ptr to non constant shared_ptr in C++?
[英]Why am I getting a crash after calling my constructor? I'm trying to push back a shared_ptr to a vector
我對編程很陌生(目前正在學習 C++)。 我正在嘗試學習如何使用智能指針。
我正在嘗試從教程中進行挑戰,其中目標是將數據點填充到向量的unique_ptr
中,該向量包含指向數據點的shared_ptr
s。 當我運行它時,它顯示 0 個錯誤和 0 個警告,所以我對出了什么問題有點迷失,因為當我開始添加數據(int)時它崩潰了。 非常感謝有關此代碼的一些幫助。 我仍然對使用智能指針感到困惑。
#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;
}
在 function 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>>>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.