简体   繁体   English

强制转换const以将其传递给具有引用功能的函数,会发生什么?

[英]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.

相关问题 如果将匿名对象传递给需要引用的函数,C ++中会发生什么? - What happens in C++ if you pass an anonymous object into a function that takes a reference? 传递非常量向量 <string> 引用了const向量的函数 <const string> ? - Pass non-const vector<string> to a function that takes a reference to const vector<const string>? 如果我将可变 lambda 作为 const 引用传递给函数会发生什么? - What will happen if I pass a mutable lambda to a function as const reference? 通过值或const引用函数? - Pass by value or const reference to function? 移入采用const左值引用的函数 - Move into a function that takes const lvalue reference 通过转换构造函数初始化const引用时会发生什么? - What happens when you initialize a const reference by conversion constructor? 当const引用绑定到临时引用时,堆栈中会发生什么? - What happens in the stack when a const reference is bound to a temporary? 持有对同一对象的const引用的对象。 退出后会发生什么? - Objects holding a const reference to the same object. What happens on exit? 返回对本地对象的 const 引用时到底发生了什么? - What exactly happens when returning const reference to a local object? C ++函数:将非const参数传递给const引用参数 - c++ function: pass non const argument to const reference parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM