Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is pair of const trivially copyable but pair is not?

Tags:

c++

std::cout << std::boolalpha;
std::cout << std::is_trivially_copyable< std::pair<const int,int> >::value;
std::cout << std::is_trivially_copyable< std::pair<int,int> >::value;

When I use GCC 9.2 the output is true false.

When I use Clang 5.0 or GCC 5.2 the output is false false.

Why the difference?

like image 779
Isaac Pascual Avatar asked Oct 08 '19 09:10

Isaac Pascual


1 Answers

std::pair has a non-trivial copy-assignment and move-assignment operator. This prevents it from being trivially copyable.

Since C++17, if one of the two contained types is not assignable, then the copy/move assignment operator is defined as deleted, which lifts this restriction on being trivially copyable. This is the case here because const int is not copy-assignable or move-assignable.

C++17 also states that if the two types have trivial destructors, then the pair will also have a trivial destructor, which is another requirement for being trivially copyable.

The older compilers you tested probably do not have full support for C++17, which prevents the pair from being trivially copyable even for pair<const int, int>.

like image 95
interjay Avatar answered Sep 22 '22 15:09

interjay