For a struct
with const
members
struct point { const int x; const int y; };
that is used as member data
struct Foo
{
point pt{ 0, 0 };
void move_x(int value);
};
How can Foo::move_x()
be written to update Foo::pt
? Is it OK to use memcpy()
?
#include <memory.h>
void Foo::move_x(int value)
{
const point pt_{ pt.x + value, pt.y };
(void) memcpy(&pt, &pt_, sizeof(pt_)); // pt = pt_;
}
This can be safely done using a pointer
#include <memory>
struct Bar
{
std::unique_ptr<point> pPt_{ new point{ 0, 0 } };
const point& pt() const {
return *pPt_;
}
void move_x(int value) {
pPt_.reset(new point{ pt().x + value, pt().y });
}
};
but the point
is then always stored on the heap rather than in Bar
.
Note that clients don't really care about point
at all:
Foo foo;
foo.move_x(314); // (314, 0)
Bar bar;
bar.move_x(3141); // (3141, 0)
point
s, why deliberately make them immutable? – Ploughboypoint
definition is thatx
andy
never change once they've been initialized. – Ploughboymemcpy
or storing the object in achar[]
. However you store or change those variables, as long as you refer topoint::x
orpoint::y
, the compiler will assume they cannot be changed and optimize certain parts of your code. The same applies when you access to apoint
through a reference. However, as you show, a pointer will help. – Dionysius