Home > database >  Can't std::move packed field in GCC, but can in CLang
Can't std::move packed field in GCC, but can in CLang

Time:10-19

Following code doesn't compile in GCC, but compiles in CLang:

See on GodBolt

#include <utility>

struct __attribute__((__packed__)) S {
    int a = 0;
};

int main() {
    S s;
    auto x = std::move(s.a); // error here
}

GCC error: <source>:9:26: error: cannot bind packed field 's.S::a' to 'int&'.

How can I fix this? Is it possible somehow to replace auto x with some packed type like int __attribute__((__packed__)) x to resolve this?

If I remove std::move then auto x = s.a; compiles in both GCC & CLang.

Note. This is only a toy minimal reproducible example. I move int in it only as example, but my real class is templated with any type T, not only int.

CodePudding user response:

This appears to work:

auto x = std::move(*&s.a);

Though this also emits

<source>:9:26: warning: taking address of packed member 'a' of class or structure 'S' may result in an unaligned pointer value [-Waddress-of-packed-member]

on both GCC and Clang.

  • Related