I'd appreciate if anybody could give me a hint on how to test for trivial copy-ability of a functor (lambdas are meant to be used). As explained in this question it is implementation defined whether lambda is trivially copyable. For example for the code shown at the end of this question gcc (5.4) and msvc (2015) both fire assertions that these are not trivially copy assignable.
I expected these types of lambdas to be represented by struct
keeping this
pointer and having copy of every captured value (if any). So they all appear to be trivially copyable - at least for the case when the captured values are trivially copyable.
My real use case driving this question is that I'm using a callback (minimalistic version of std::function
that does not allocate and is meant for very simple functors) that keeps a fixed buffer in which it copy constructs (in place) passed functor. Then I expected to be able to copy/assign these callbacks but in order for this to work (out of the box) simple mem-copying of these fixed buffers should be equivalent to coping/assigning of the functors kept in them.
So I have two questions:
-
Imagine that in
test_functor()
below I donew
placement e.g. likenew (&buffer) F(functor)
Is it save to just mem-copy this buffer for the kind of lambdas shown below? I expect this should be so since for all cases there is only
this
pointer captured or values captured are trivially copyable, but it would be nice if somebody could confirm this. -
How can I test whether simple copying of memory where functor is kept is equivalent to copying of the functor? If the answer for the first question is positive then
std::is_trivially_copy_assignable
not the right answer.
I'd appreciate your help/pointers...
Best regards
#include <type_traits>
template <typename F>
void test_functor(const F& functor)
{
static_assert(std::is_trivially_destructible<F>::value,
"Functor not trivially destructible");
static_assert(std::is_trivially_copy_constructible<F>::value,
"Functor not trivially copy constructible");
static_assert(std::is_trivially_copy_assignable<F>::value,
"Functor not trivially copy assignable");
}
struct A
{
void test() { test_functor([this]() { }); }
};
struct B
{
void test() { test_functor([this](int v) { value = v; }); }
int value;
};
struct C
{
void test(int v) { test_functor([=]() { value = v; }); }
int value;
};
int main()
{
A a;
B b;
C c;
a.test();
b.test();
c.test(1);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire