cast接着修改一个ref

cast接着修改一个ref

本文介绍了我是说,const_cast接着修改一个ref-to-const绑定到一个临时是好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想查看我对此事的理解和结论。 在IRC上, / p> 翻译 -const绑定到一个临时,他想放弃其 const - 修改它。 我的回答是,我问了一个类似的问题以前,其中共识似乎是暂时本身不是固有的 const ,因此,你可以抛弃 const 一个引用你有他们,并通过结果修改它们。并且,只要原始引用 - const 仍然存在,这不会影响临时的生命周期。 这是: int main() { const int& x = int(3); int& y = const_cast< int&>(x); y = 4; cout<< X; } //输出:4 // ^法律和安全 我可以吗? (当然,事物完全!) 解决方案 否。 首先,据我所知,它是否为字面值是无关紧要。非类类型的R值总是具有非cv限定的类型(§3.10/ 9),然而,在§8.5.3(引用的初始化)中,我们有:(上述所有点都涉及左值或类类型。) 在我们的例子中,我们有: int const& x = ...; 所以 cv1 T1 是 int const ,我们创建的临时对象类型为 int const 。这是一个顶级const(在对象上),所以任何尝试修改它是未定义的行为。 至少,这是我的解释。我希望标准更清楚这一点。 I would like to check my understanding and conclusions on this matter.On IRC, it was asked:Translating: he has a ref-to-const bound to a temporary, and he wants to cast away its const-ness to modify it.My response was that I'd asked a similar question previously, where the consensus seemed to be that temporaries themselves are not inherently const, and thus that you can cast off the const-ness of a reference you have to them, and modify them through the result. And, as long as that original ref-to-const still exists, this won't affect the temporary's lifetime.That is:int main(){ const int& x = int(3); int& y = const_cast<int&>(x); y = 4; cout << x;}// Output: 4// ^ Legal and safeAm I right?(Of course, whether or not such code is actually advisable is another matter entirely!) 解决方案 No.First, as far as I can tell, whether it is a literal or not isirrelevant. Rvalues of non-class types always have non-cv qualifiedtypes (§3.10/9), however, in §8.5.3 (initialization of a reference), wehave:(All of the preceding points concern either lvalues or class types.)In our case, we have:int const& x = ...;So cv1 T1 is int const, and the temporary object we create has typeint const. This is a top level const (on the object), so any attemptto modify it is undefined behavior.At least, that's my interpretation. I wish the standard were a bit clearer about this. 这篇关于我是说,const_cast接着修改一个ref-to-const绑定到一个临时是好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-01 02:11