Std :: copy / memcpy / memmove optimization

I looked into GCC STL (4.6.1) and saw that std::copy() uses the optimized version if the built-in __is_trivial() is true .

Since the std::copy() and std::reverse_copy() patterns are very useful for copying elements in arrays, I would like to use them. However, I have several types (which are examples of template instances) that are structures that contain some trivial values, without pointers, and don't have a constructor or assignment operator.

Is g ++ smart enough to realize that my type is actually trivial? Is there a way in C ++ 98 to make sure that the STL implementation knows that my type is trivial?

I think that in C ++ 11 everything will become more convenient using a trait like is_trivial<> . Is it correct?

Thanks!

EDIT: Sorry to be so late, but here is an example of a fairly simple Type class that is not trivial for GCC and llvm. Any ideas?

 #include <iostream> struct Spec; template <typename TValue, typename TSpec> class Type { public: TValue value; Type() : value(0) {} }; int main() { std::cerr << "__is_trivial(...) == " << __is_trivial(Type<char, Spec>) << '\n'; return 0; } 
+6
source share
2 answers

There was some debate about what trivial meant.

For example, your example is not trivially constructive as far as I can tell ( std::is_trivially_default_constructible will return false, I think).

In your case, I think you will need a new attribute std::is_trivially_copyable , which is finer. So ... upgrade your compiler?

+5
source

__is_trivial gives the correct value for all types.

You cannot rely on any PATLAL STL implementation to use it, although if the compiler provider provided it, it probably contains various improvements related to the compiler, off-screen.

C ++ 11 std::is_trivial is just a standardization of this function, there is no reason not to use it.

+4
source

Source: https://habr.com/ru/post/906322/


All Articles