Following the discussion on my answer to this question, apparently:
The following Code is 允许
struct Foo {
int x;
};
Foo f;
Foo & f_ref = f;
(&f) -> ~Foo ();
new (&f) Foo ();
int x = f_ref .x;
but the following code is not allowed
struct Foo {
const int & x; // difference is const reference
Foo (int & i) : x(i) {}
};
int i;
Foo f (i);
Foo & f_ref = f;
(&f) -> ~Foo ();
new (&f) Foo (i);
int x = f_ref .x;
Because of $3.8/7
如果在物体的寿命结束后,在所占领物体的储存被再利用或释放之前,在原物体所占领的储存地点制造了新的物体,指明原物体的点子,提及原始物体的参考资料,或原始物体的名称,将自动提及新物体,一旦新物体的寿命开始,即可用来操纵新物体,条件是:
- the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type ...
我可以理解,如何提及<代码>f.x。 如果不复存在,则可能无效,但我看不出为什么f_ref
。 纯粹因为其成员中某一成员是混淆和(或)参照的,而不应有:它是指<代码>。 Foo before and is a reference to a 之后的Foo
。
是否有人解释这一条件的理由?
Edit
感谢答复。 我不赞成“保证不作任何改动”的论点,因为我们don t目前允许选择异见者到切指,例如:
struct Foo {
const int & x;
Foo (const int & i) : x(i) {}
void do_it ();
};
int i;
Foo f (i);
const int & ii = f.x;
f .do_it (); // may modify i
std :: cout << ii; // May NOT use cached i
I don t see how do_it
is allowed to invalidate referenced values but operator new
isn t -- Sequence points invalidate cached values: why should delete/placement-new be exempt?