什么保证重载的非const方法被调用
What guarantees that the overloaded non-const method is invoked?
给定这两个修改和返回字符串的函数:
// modify the original string, and for convenience return a reference to it
std::string &modify( std::string &str )
{
// ...do something here to modify the string...
return str;
}
// make a copy of the string before modifying it
std::string modify( const std::string &str )
{
std::string s( str );
return modify( s ); // could this not call the "const" version again?
}
这段代码使用GCC g++为我工作,但我不明白为什么/如何。我担心第二个函数会调用自己,让我失去控制递归,直到堆栈耗尽。这能保证有效吗?
您有两个重载函数:
std::string &modify( std::string &str )
std::string modify( const std::string &str )
传递的是一个非const限定的std::string
。因此,接受非const限定参数的函数更合适。如果不存在,编译器可以将非const限定字符串转换为const限定字符串以进行调用,但对于函数重载,不需要转换的调用比需要转换的调用更适合。
return modify( s ); // could this not call the "const" version again?
。它是而不是递归。它将调用参数为std::string &
的另一个重载。
这是因为表达式s
的类型为std::string &
,与另一个重载函数的参数类型相匹配。
为了递归,调用点的实参需要转换为std::string const &
。但是在您的例子中,这种转换是不必要的,因为存在不需要转换的重载
这不是递归,而是重载。当你调用第二个函数时,它的参数是一个常量字符串。在这个函数内部,你调用另一个接受非const字符串的函数。你所做的是剥离字符串的const-ness,更好的方法是使用const_cast。
我将链接到另一个stackoverflow线程
相关文章:
- 从 const 对象访问非 const 方法
- 为什么我可以调用一个从const方法更改成员的方法
- 使用新的c++返回值语法的Const方法
- const_cast const 方法中的"this"将"this"分配给外部变量?
- const 方法使用引用修改对象
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 返回非常量引用编译的 Const 方法
- C++:无法从 const 方法返回对象的shared_ptr
- 是否可以从 const 方法迭代链表
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- 在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量
- "可变"变量只能由 const 方法之一可变?
- Golang中的const方法
- C++ 逻辑恒常性和 const方法的按值返回
- c++将标志添加到const方法中
- C++防止const方法通过成员指针或引用更改数据
- 为什么 const 方法不覆盖 C++ 中的非 const 方法?
- 如何在const方法中迭代映射
- 为什么没有标准化的方法来避免const方法的代码重复
- 修改 const 方法中的 pointee 值