Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 933
user5814611 Avatar asked May 30 '26 20:05

user5814611


1 Answers

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

like image 73
101010 Avatar answered Jun 01 '26 12:06

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!