简体   繁体   English

使用基于范围的for循环将对象emplace_back到向量中的正确方法是什么? C ++

[英]What is the correct way to emplace_back an object into a vector using the range-based for loop? C++

I have an object that I want to add it to the vector container, but I would like to know is that 2 ways I did the same thing? 我有一个对象想要将其添加到向量容器中,但是我想知道这是我做同一件事的两种方式吗? And what is the correct way to do it? 正确的方法是什么?

The reason why I did m_boid.emplace_back(std::move(bird)); 我之所以m_boid.emplace_back(std::move(bird)); is because bird is a range-based-for-loop variable and if I don't use bird it will prompt me a warning saying Unsed variable bird But program is still able to run as it's not an error. 这是因为bird是一个基于范围的循环变量,如果我不使用bird ,则会提示我一个警告,提示Unsed变量bird但是程序仍然可以运行,因为这不是错误。

What is the correct way to emplace_back an object into a vector using the range-based for loop? 使用基于范围的for循环将对象emplace_back到向量中的正确方法是什么?

Thank you in advance. 先感谢您。

Boid::Boid(int size)
{
    m_boid.resize(size);  //vector of unique pointer

    for(auto &bird : m_boid)
    {
        //Create an object
        m_obj.reset(new Boid); //unique pointer

            // Add object to vector. Is this 2 below the same thing?
            m_boid.emplace_back(std::move(bird));  //Should I do this?
            m_boid.emplace_back(std::move(m_obj)); //Or should I do this?
    }
}



EDITED. 编辑。 HOW ABOUT THIS? 这个怎么样? is this ok? 这个可以吗?

void Boid::initBoid(unsigned int containSize)
{

    m_boid.resize(containSize);

    for(auto &bird : m_boid)
    {
        bird.reset(new Boid);
        bird->createVAO();
    }
}

What is the correct way to emplace_back an object into a vector using the range-based for loop? 使用基于范围的for循环将对象emplace_back到向量中的正确方法是什么?

I'd say none. 我不会说。 emplace_back could invalidate iterators in case of a reallocation, thus you'd get an UB in that case. 在重新分配的情况下, emplace_back可能会使迭代器无效,因此在这种情况下,您将获得一个UB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM