No problem to assign one struct to another by value when they both have the same type...
#include <iostream>
using namespace std;
struct t {
int y;
};
int main()
{
t a={1};
t b;
b=a;
cout<< a.y << '\n';
cout<< b.y << '\n';
return 0;
}
..which prints two 1
s as expected. But if I modify the source struct to be volatile
, like this...
#include <iostream>
using namespace std;
struct t
{
int y;
};
int
main ()
{
volatile t a = { 1 };
t b = a;
cout << a.y << '\n';
cout << b.y << '\n';
return 0;
}
(https://onlinegdb.com/McFd3jJ_r)
...then I get compiler errors like...
.main.cpp: In function ‘int main()’:
main.cpp:24:9: error: no matching function for call to ‘t(volatile t&)’
24 | t b = a;
| ^
main.cpp:13:8: note: candidate: ‘constexpr t::t(const t&)’ (near match)
13 | struct t
| ^
main.cpp:13:8: note: conversion of argument 1 would be ill-formed:
main.cpp:24:9: error: binding reference of type ‘const t&’ to ‘volatile t’ discards qualifiers
24 | t b = a;
| ^
main.cpp:13:8: note: candidate: ‘constexpr t::t(t&&)’ (near match)
13 | struct t
| ^
main.cpp:13:8: note: conversion of argument 1 would be ill-formed:
main.cpp:24:9: error: cannot bind rvalue reference of type ‘t&&’ to lvalue of type ‘volatile t’
24 | t b = a;
| ^
Why am I not able to read from a volatile
struct to assign it to another struct?
I can manually go through and assign each of the members from the volatile
source to the destination and this works fine, but this is not good for abstraction because now the code doing the assignment needs to know all of the members.
What is the correct way to do struct assignments by value when the source struct are volatile?