编写两个方法的最佳方法,这些方法在C++中返回同一项的值和引用

Optimal way to write two methods that return a value and reference of the same item in C++

本文关键字:方法 返回 一项 引用 C++ 两个 最佳      更新时间:2023-10-16

>假设我有一个有两个方法的类。 其中一个应该在容器中找到一个对象并按值返回它,另一个应该通过引用返回它。 当然,我希望第一种方法是const的(在thisconst的意义上),而第二种方法不是。

有没有办法在这两种方法之间重用代码,而不引入它们都依赖的第三种方法? 下面我举了一个玩具例子,人们应该想象find步骤实际上要复杂得多。

在下面的"可能的实现 1"中,由于我从内部调用(constconst)get_refget_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 );
}

要直接回答这个问题,避免使用第三种/私有方法的唯一方法是抛弃thisconst性。

使用"可能的实现 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