可以使用memcpy()来改变“const”会员数据? [英] can memcpy() be used to change "const" member data?
问题描述
struct
与 const
成员
struct point {const int x; const int y; };
用作成员数据
struct Foo
{
point pt {0,0};
void move_x(int value);
};
如何 Foo :: move_x()
写入更新 Foo :: pt
?是否可以使用 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_;
}
这可以使用指针安全完成
#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()。
}
};
但点
请注意,客户端并不真正关心。
Foo foo;
foo.move_x(314); //(314,0)
条形栏;
bar.move_x(3141); //(3141,0)
行为。现在,可以这样做?当然,它可以,但只是在编译器不会抱怨的意义上。但是C ++的一个方面只是因为编译器不会抱怨它并不意味着所产生的代码将正常工作。
这只是时间问题写一些读取 pt
的代码,调用 move_x()
,然后读取 pt
。
现代的优化编译器会合理地假设因为代码读取 const
使用从 pt 的第一次读取缓存的数据,继续并优化从
pt
code>,在CPU寄存器中。
然后,不幸的程序员将花一个星期试图找出为什么代码显然不是做什么程序说应该这样做。
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)
This is clearly undefined behavior. Now, "can" this be done? Sure, it can, but only in the sense that the compiler will not complain. But one aspect of C++ is just because the compiler doesn't complain it doesn't mean that the resulting code will work right.
It's only a matter of time before someone writes some code that reads pt
, calls move_x()
, and then reads pt
again.
A modern, optimizing compiler will rightfully assume that because the code is reading const
instances, their values cannot change, and then proceed and optimize away the second read from pt
, using the data cached from the first read of pt
, in the CPU registers.
And then, the hapless programmer will spend a week trying to figure out why the code is clearly not doing what the program says it should be doing.
这篇关于可以使用memcpy()来改变“const”会员数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!