Why can't std::tuple be trivially copyable?

后端 未结 2 1003
陌清茗
陌清茗 2020-12-15 10:25

Built with this online compiler, the following code:

#include 
#include 
#include 

int main() {
    std::cou         


        
相关标签:
2条回答
  • 2020-12-15 10:27

    Because std::tuple has copy/move ctor and assignment operators, it makes the class not-trivially-copyable.

    See cpp reference:

    A trivially copyable class is a class that

    Has no non-trivial copy constructors (this also requires no virtual functions or virtual bases)
    Has no non-trivial move constructors
    Has no non-trivial copy assignment operators
    Has no non-trivial move assignment operators
    Has a trivial destructor
    

    But std::tuple has all of the above constructors and assignment operators.

    0 讨论(0)
  • 2020-12-15 10:34

    The thing that trips pair up as far as trivial copyability is concerned is that the standard does not require that the copy/move assignment operators be trivial. The standard explicitly declares that the copy/move constructors are defaulted, but not so for the assignments. An implementation could default them as well, but the standard does not require it.

    There's no really good reason why the standard doesn't require it. But it doesn't.

    For tuple, things are a lot more complicated. Many tuple implementations are based on having a storage buffer of the right size/alignment, and using placement new to construct the individual members within that buffer. That's all fine and good, but such a type has to implement a manual copy/move constructor, since it must call the copy/move constructor of each type. Even if it knew that they were all trivially copyable and copied them via memcpy, that's still a manual operation. And that disqualifies it from trivial copyability.

    Now, there are implementations of tuple which could be trivially copyable if the types are trivially copyable. But there is no requirement to implement them that way. And it would complicate tuple implementations tremendously to do require them to implement themselves one way if all the types are trivially copyable, and implement them in a different way otherwise.

    0 讨论(0)
提交回复
热议问题