std::copy/memcpy/memmove optimizations

二次信任 提交于 2019-12-21 11:25:36

问题


I looked into the GCC STL (4.6.1) and saw that std::copy() uses an optimized version in case the builtin __is_trivial() evaluates to true.

Since the std::copy() and std::reverse_copy() templates are very useful for copying elements in arrays, I would like to use them. However, I have some types (which are results of template instantiations) that are structs that contain some trivial values, no pointers and have no copy constructor or assignment operator.

Is G++ smart enough to figure out that my type in fact is trivial? Is there any way in C++98 to make sure an STL implementation knows that my type is trivial?

I guess that in C++11, things will become convenient using the is_trivial<> type trait. Is this right?

Thanks!

EDIT: Sorry for being so late with this, but here is an example of a pretty simple Type class that is not trivial to 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;
} 

回答1:


There has been some debate over what trivial meant.

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

In your case, I think you would need the new trait std::is_trivially_copyable, which is more fine grained. So... upgrade your compiler ?




回答2:


__is_trivial gives the right value for all types.

You can't rely on any paticular STL implementation to use it, although if the compiler vendor supplied it then it probably does contain various compiler-specific improvements behinds the scenes.

C++11's std::is_trivial is merely standardising this feature, there's no reason for an implementation not to use it.



来源:https://stackoverflow.com/questions/8913747/stdcopy-memcpy-memmove-optimizations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!