[英]How can I create objects using a vector, for loop & unique pointers?
I have a project for uni and I must create 3 objects(unique pointers) using a vector.我有一个 uni 项目,我必须使用向量创建 3 个对象(唯一指针)。 What do I do wrong with this code?
这段代码我做错了什么? Would be really happy if you could help me out with this.
如果你能帮我解决这个问题,我会很高兴。
void vAufgabe_1a() {
const int num_obj = 3;
for (int i = 0; i != num_obj; i++) {
auto FZ[i] = make_unique<Fahrzeug>(); // FZ[i] doesn't work here.
FZ[i].push_back(move(make_unique <Fahrzeug>));
cout << "Der Name des Fahrzeugs: " << endl;
cin << FZ[i]->p_sName;
}
}
I wouldn't make a vector of unique pointers to objects at all (it will A: be harder, B: a double indirection).我根本不会制作指向对象的唯一指针向量(它会 A:更难,B:双重间接)。 A vector will already do all the memory managment for you.
向量已经为您完成所有 memory 管理。 Live demo here: https://onlinegdb.com/SeLMTl2Zz
现场演示: https://onlinegdb.com/SeLMTl2Zz
#include <iostream>
#include <memory>
#include <vector>
//-----------------------------------------------------------------------------
// (Fahrzeug, but then in English)
class Vehicle
{
public:
// give each vehicle a unique instance number
Vehicle() :
m_id{ ++s_id }
{
std::cout << "Constructed vehicle : " << m_id << "\n";
}
// show when object is destructed (and why unique_ptr is not needed)
~Vehicle()
{
std::cout << "Destructed vehicle : " << m_id << "\n";
}
std::size_t get_id() const
{
return m_id;
}
private:
static std::size_t s_id;
std::size_t m_id;
};
//-----------------------------------------------------------------------------
// initialize id generating number
std::size_t Vehicle::s_id{ 0ul };
// don't use magic numbers in code, give your constants names
const std::size_t number_of_vehicles = 3ul;
//-----------------------------------------------------------------------------
int main()
{
// create a scope to manage lifecycle of the vector of vehicles
// so I can show the destruction phase more clearly
{
// you can initialize vectors from the constructor
std::cout << "Creating vector with vehicles\n";
std::vector<Vehicle> vehicles(number_of_vehicles);
for (const auto& vehicle : vehicles)
{
std::cout << vehicle.get_id() << "\n";
}
std::cout << "Destructing vector with vehicles\n";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.