casting non const to const in c++

2019-03-10 23:25发布

I know that you can use const_cast to cast a const to a non-const.

But what should you use if you want to cast non-const to const?

6条回答
男人必须洒脱
2楼-- · 2019-03-10 23:41

You can use a const_cast if you want to, but it's not really needed -- non-const can be converted to const implicitly.

查看更多
Evening l夕情丶
3楼-- · 2019-03-10 23:42

You have an implicit conversion if you pass an non const argument to a function which has a const parameter

查看更多
▲ chillily
4楼-- · 2019-03-10 23:47

const_cast can be used in order remove or add constness to an object. This can be useful when you want to call a specific overload.

Contrived example:

class foo {
    int i;
public:
    foo(int i) : i(i) { }

    int bar() const {
        return i;    
    }

    int bar() { // not const
        i++;
        return const_cast<const foo*>(this)->bar(); 
    }
};
查看更多
我命由我不由天
5楼-- · 2019-03-10 23:51

STL since C++17 now provides std::as_const for exactly this case.

See: http://en.cppreference.com/w/cpp/utility/as_const

Use:

CallFunc( as_const(variable) );

Instead of:

CallFunc( const_cast<const decltype(variable)>(variable) );
查看更多
干净又极端
6楼-- · 2019-03-10 23:54

const_cast can be used to add constness behavior too.

From cplusplus.com:

This type of casting manipulates the constness of an object, either to be set or to be removed.

查看更多
迷人小祖宗
7楼-- · 2019-03-11 00:06

You don't need const_cast to add constness:

class C;
C c;
C const& const_c = c;

Please read through this question and answer for details.

查看更多
登录 后发表回答