简体   繁体   English

无需复制即可置入向量

[英]Emplace back to vector without copying

I have a vector of non-copyable objects and I need to use emplace_back() to add to the vector.我有一个不可复制对象的向量,我需要使用emplace_back()添加到向量中。 Obviously that gets a error that its trying to reference a deleted function because it is non-copyable.显然,它会尝试引用已删除的函数,因为它是不可复制的,因此会出现错误。 I was just wondering, is there even a way to do this?我只是想知道,有没有办法做到这一点? I am more specifically trying to have a vector of sfml's render windows.我更具体地说是尝试拥有一个 sfml 渲染窗口的向量。

My Main我的主要

int main()
{
    sf::RenderWindow window(sf::VideoMode(100, 100, 32), "Main Window", sf::Style::Default);
    MakeKey MakeKey;
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            //Key Presses
            if (event.type == sf::Event::KeyPressed) {
                if (event.key.code == sf::Keyboard::A)
                    MakeKey.DrawKey("A");
                else if (event.key.code == sf::Keyboard::D)
                    MakeKey.DrawKey("D");
                //Ect
            }
            if (event.type == sf::Event::Closed)
                window.close();
        }
        MakeKey.StepWindows();
    }
    return EXIT_SUCCESS;
}

My DrawKey Function我的 DrawKey 功能

void MakeKey::DrawKey(string input)
{
    MakeKey::NewKey Key;
    if (input == "A")
        Key.Img.loadFromFile("Assets/Images/A.png");
    else if (input == "D")
        Key.Img.loadFromFile("Assets/Images/D.png");
    //Ect
    sf::RenderWindow window(sf::VideoMode(Key.Img.getSize().x, Key.Img.getSize().y, 32), "Key", sf::Style::None);
    Key.Tex.loadFromImage(Key.Img);
    Key.Sprite.setTexture(Key.Tex);
    KeyArray.emplace_back(std::move(Key));
    WindowArray.push_back(std::move(window));
    cout << "KeyArray Has " << KeyArray.size() << " Elements\n" << "WindowArray Has " << WindowArray.size() << " Elements" << endl;
}

My StepWindows Function我的 StepWindows 功能

void MakeKey::StepWindows()
{
    for (int i{ 0 }; i > KeyArray.size(); i++)
    {
        cout << "Inside Step Windows For Loop" << endl;
        WindowArray[1].setActive(true);
        WindowArray[1].clear(sf::Color::Transparent);
        WindowArray[1].draw(KeyArray[1].Sprite);
        WindowArray[1].display();
    }
}

To use either std::vector<T>::push_back() or std::vector<T>::emplacy_back() The type T is required to have either a copy constructor or a noexcept move constructor.使用std::vector<T>::push_back()std::vector<T>::emplacy_back()需要类型T具有复制构造函数或 noexcept 移动构造函数。 Please pay special attention that the requirement for the move constructor to be noexcept is important: that allows to keep exception safity while the buffer reallocation.请特别注意移动构造函数为noexcept的要求很重要:这允许在缓冲区重新分配时保持异常安全。

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

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