c++ - const_cast<const string &>(s), while s 是字符串类型怎么办?

标签 c++ const-cast

我问了一个related, tedious question以前和现在我发现了一些新东西。

#include <iostream>
#include <string>
using namespace std;
void hello (const string &s1) {
    cout << "rocky" << endl;
}

void hello(string &s1) {
    cout << "banana" << endl;
}
int main()
{   
    string s = "abc";
    hello(const_cast<const string&>(s));  //how to explain this const_cast?
}

hello(const_cast<const string&>(s));这有效并匹配 const 引用参数函数。那么这次的转化情况如何呢?是不是stringconst string&

当然我知道 const 引用可以用非 const 对象初始化......但不知何故我从不把它当作一个转换。我将其视为一项任务。我认为引用类型和引用类型是两种截然不同的东西。

最佳答案

因此,转换的主要含义是从重载的 hello() 函数列表中选择必要的一个。没有强制转换,我们选择非 const 版本,否则就是 const 版本。

其次,为什么要转换字符串引用,而不仅仅是字符串类型?这是 const_cast 本身的局限性。让我们尝试编译它:

hello(const_cast<const string>(s));  // we removed the "&"

编译器消息:

error: invalid use of const_cast with type ‘const string {aka const std::__cxx11::basic_string<char>}’,
which is not a pointer, reference, nor a pointer-to-data-member type

因此,const_cast 并不是为了创建新实例,而是间接地使用给定实例,并且只是更改关联的 CV 限定(因为它是代码生成方面的免费午餐)。因此,我们必须处理指针或引用以符合该条件。

附言据我所知,C++17 允许为转换创建临时拷贝(也称为临时物化),因此我们的非引用尝试可能具有实际意义。同时,这是一个很新的概念,并没有那么广泛。

关于c++ - const_cast<const string &>(s), while s 是字符串类型怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49800593/

相关文章:

c++空队列初始化在Qt Creator中不为空

Python C++ API : How to retrieve lineno attribute of NameError

c++ - Const 类型转换空基类

c++ - 将 const char* 转换为 QString

c++ - 是否有理由在此代码中的字符串文字上使用 const_cast ?

c++ - 如何在成对集合上使用 lower_bound()?

c++ - 如果 pthread_cond_wait 在 pthread_cond_signal 信号之前丢失信号

c++ - 头文件中的怪异

c++ - 是否可以将一对 <Key, Value> 转换为一对 <const Key, Value>?

c++ - 定义数组时是否可以接受const_cast?