Mar 21, 2018

[C++] volatile struct type instance copy

volatile struct = struct not possible, why?



This is ill-formed because FOO has an implicit copy constructor defined as: FOO(FOO const&);


And you write FOO test = foo; with foo of type volatile FOO, invoking: FOO(volatile FOO const&);


But references-to-volatile to references-to-non-volatile implicit conversion is ill-formed.

From here, two solutions emerge:
  • don't make volatile to non-volatile conversions;
  • define a suited copy constructor or copy the object members "manually";
  • const_cast can remove the volatile qualifier, but this is undefined behavior to use that if your underlying object is effectively volatile.

Could I possibly use memcopy() for that?

No you cannot, memcpy is incompatible with volatile objects: thre is no overload of it which takes pointers-to-volatile, and there is nothing you can do without invoking undefined behavior.

So, as a conclusion, your best shot if you cannot add a constructor to FOO is to define:
FOO FOO_copy(FOO volatile const& other) { 

FOO result; 

result.a = other.a; 

result.b = other.b;

result.c = other.c;

return result; }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.