3

我正在使用“emplace”方法来避免内存复制。但是,当我在 Lambda 函数中使用“emplace”时。它总是调用隐式移动构造函数。如何避免 Lambda 函数中的内存复制?此示例程序不应打印“我正在被移动”。</p>

#include <vector>
#include <iostream>

struct A
{
    int a;

    A(int t) : a(t)
    {
        std::cout << "I am being constructed.\n";
    }
    A(A&& other) : a(std::move(other.a))
    {
        std::cout << "I am being moved.\n";
    }
};

std::vector<A> g_a;

int main()
{
    std::cout << "emplace_back:\n";
    g_a.emplace_back(1);

    std::cout << "emplace_back in lambda:\n";
    auto f1 = [](int x) { g_a.emplace_back(x);  };  
    f1(2);

    std::cout << "\nContents: ";
    for (A const& t : g_a) 
        std::cout << t.a << " ";
    std::cout << std::endl;
}
4

1 回答 1

6

这不是关于 lambda 函数,而是关于重新分配其内存的向量。您可以使用std::vector::reserve.

int main() {
    g_a.reserve(10);
    ^^^^^^^^^^^^^^^^
    std::cout << "emplace_back:\n";
    g_a.emplace_back(1);

    std::cout << "emplace_back in lambda:\n";
    auto f1 = [](int x) { g_a.emplace_back(x);  };  
    f1(2);

    std::cout << "\nContents: ";
    for (A const& t : g_a) 
        std::cout << t.a << " ";
    std::cout << std::endl;
}

现场演示

于 2016-01-20T09:01:01.917 回答