编写两个方法的最佳方法,这些方法在C++中返回同一项的值和引用
Optimal way to write two methods that return a value and reference of the same item in C++
>假设我有一个有两个方法的类。 其中一个应该在容器中找到一个对象并按值返回它,另一个应该通过引用返回它。 当然,我希望第一种方法是const
的(在this
被const
的意义上),而第二种方法不是。
有没有办法在这两种方法之间重用代码,而不引入它们都依赖的第三种方法? 下面我举了一个玩具例子,人们应该想象find
步骤实际上要复杂得多。
在下面的"可能的实现 1"中,由于我从内部调用(const
非const
)get_ref
get_value
,因此存在错误。 在"可能的实现 2"中,引用是从值的临时副本创建的,这当然是一个主要问题。
如果需要const
引用,那么当然没有问题,但假设我实际上想要一个普通引用。
// Header:
#include <string>
#include <map>
using std::string;
using std::map;
class Test {
public:
map< string, string > stuff;
string & get_ref( const string key );
string get_value( const string key ) const;
};
// Possible implementation 1:
string Test::get_value( const string key ) const {
return get_ref( key );
}
string & Test::get_ref( const string key ) {
return stuff.find( key )->second;
}
// Possible implementation 2 (obviously wrong, but here for the sake of pointing that out):
string Test::get_value( const string key ) const {
return stuff.find( key )->second;
}
string & Test::get_ref( const string key ) {
return get_value( key );
}
要直接回答这个问题,避免使用第三种/私有方法的唯一方法是抛弃this
的const
性。
使用"可能的实现 1",更改如下:
string Test::get_value( const string key ) const {
return const_cast<Test*>(this)->get_ref( key );
}
现在,更广泛地了解另外两个问题:首先,您应该更改get_ref()
以便在stuff.find( key )
返回end()
(一遍于尾迭代器)时执行一些明智的操作。选项包括引发异常或返回空字符串。
其次,一个简单的效率改进是注意方法参数按值传递字符串,可以轻松安全地更改字符串以传递const string& key
。
相关文章:
- 从父类方法返回子类对象
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 让bool方法返回其他整数
- 不能将方法返回的值用于另一个方法
- 从私有成员变量的成员方法返回unique_ptr
- 我的模板类方法返回错误类型?
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 我无法使用C++指针指向类方法返回的 std::vector
- 对象引用中的字段以不同的方法返回不同的值
- 类方法返回指向具有模板的类成员的指针
- 如何将字符串从 C++/CLI 方法返回到调用它的非托管C++
- 从工厂方法返回的ComPtr的引用计数增加两次
- 如何使用 SFINAE 从 end() 方法返回 (const_) 迭代器
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- 从类方法返回 "const char*" 作为 std::string&
- 如何使用 "get" 方法返回类的私有 std::unique_ptr 成员
- 可能从单个方法返回不同类型的对象
- qml 未知方法返回类型:ArchiveFile*,即使调用了 qmlRegisterUncreatableType
- 如何从方法返回静态常量 int std::array?
- 当从其他方法返回 vector 时,C++无法访问矢量元素