【问题标题】:How can I create objects using a vector, for loop & unique pointers?如何使用向量、for 循环和唯一指针创建对象?
【发布时间】:2022-01-08 01:46:28
【问题描述】:

我有一个 uni 项目,我必须使用向量创建 3 个对象(唯一指针)。 这段代码我做错了什么? 如果你能帮我解决这个问题,我会很高兴。

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;

    }
}

【问题讨论】:

  • std::vector&lt;std::unique_ptr&lt;Fahrzeug&gt;&gt; FZ; 应该在循环之外。
  • std::movestd::move(std::make_unique&lt;Fahrzeug&gt;()) 中没用。 (std::move(FZ[i]) 可能需要它)。

标签: c++ vector unique-ptr


【解决方案1】:

我根本不会创建指向对象的唯一指针向量(它会 A:更难,B:双重间接)。向量已经为您完成了所有的内存管理。现场演示: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;
}

【讨论】:

  • 向量 和向量> 是两个非常不同的东西。哪一个更有意义完全取决于用例以及您的对象的外观。您不应该做出绝对的陈述,例如“永远不要创建指向对象的唯一指针向量”。这样做是有原因的。
  • 我的意思是应该有充分的理由添加额外的间接级别。付出额外的努力和复杂性一定是值得的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2021-07-30
相关资源
最近更新 更多