user5814611
user5814611

Reputation: 61

How Can I avoid implicit move constructor inside a lambda function

I am using "emplace" method to avoid memory copy. But, when I am using the "emplace" inside a Lambda function. It always call implicit move constructor. How I can avoid memory copy inside a Lambda function? This sample program should not print “I am being moved.”

#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;
}

Upvotes: 3

Views: 237

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42909

It's not about the lambda function but rather about the vector that reallocates its memory. You can ammend this with 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;
}

Live Demo

Upvotes: 6

Related Questions