[英]casting const to pass it to function that takes reference, what happens?
Can anyone tell me what happens here when passing to g in the main, is it static_cast? 谁能告诉我在传递给main中的g时会发生什么,它是static_cast吗?
int & g (int&x){x++ ; return x ; }
int main()
{
const int a=5 ;
cout<<g((int&)a)<<endl;
}
I am sure that no copy is made, since the code above is similar to the one below : 我确信不会复制,因为上面的代码类似于下面的代码:
class A
{
public:
A()
{
cout << "calling DEFAULT constructor\n\n";
}
A(A& Other)
{
cout << "Calling COPY constructor\n\n";
}
~A()
{
cout << "Calling DESTRUCTOR\n\n";
}
};
A& g(A& x)
{
cout << "Inside g(A& x) \n\n";
return x;
}
void main()
{
const A a;
g(const_cast<A&>(a));
}*/
Thanks in advance :) 提前致谢 :)
static_cast
cannot remove constness. static_cast
无法删除常量。 This is a const_cast
. 这是
const_cast
。
At runtime, this code (the first example) yields undefined behavior because you modify a const object. 在运行时,此代码(第一个示例)产生未定义的行为,因为您修改了const对象。
A C-style cast is a vicious thing -- it will do everything that a reinterpret_cast<>
or a const_cast<>
will do. C风格的强制转换是一件恶毒的事情,它将完成
reinterpret_cast<>
或const_cast<>
。 It's one of those "the power of a chainsaw with the ease-of-use of a chainsaw" things that C is rightly infamous for. 这是C正确的臭名昭著的“电锯的力量和易用的电锯”之一。
Using the C++-style casts will show that you need to do a const_cast<>
, and then you should ask yourself why and find a better way to do it. 使用C ++样式的强制类型转换将表明您需要执行
const_cast<>
,然后您应该问自己为什么,并找到一种更好的方法。
对于int,不需要传递引用的任何代码。您的强制转换可以对其进行编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.