如何删除类似的const和非const成员函数之间的代码复制?
假设我有以下 class X
,我想要返回内部成员的访问权限:
Let's say I have the following class X
where I want to return access to an internal member:
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const Z& Z(size_t index) const
{
// identical to non-const X::Z(), except printed in
// a lighter shade of gray since
// we're running low on toner by this point
}
};
两个成员函数 X :: Z()
和 X :: Z()const
在大括号中有相同的代码。这是重复的代码,可能会对具有复杂逻辑的长函数造成维护问题。
The two member functions X::Z()
and X::Z() const
have identical code inside the braces. This is duplicate code and can cause maintenance problems for long functions with complex logic.
有没有办法避免这种代码重复?
Is there a way to avoid this code duplication?
是的,可以避免代码重复。你需要使用const成员函数具有逻辑并使非const成员函数调用const成员函数并将返回值重新转换为非const引用(如果函数返回指针,则为指针):
Yes, it is possible to avoid the code duplication. You need to use the const member function to have the logic and have the non-const member function call the const member function and re-cast the return value to a non-const reference (or pointer if the functions returns a pointer):
class X
{
std::vector<Z> vecZ;
public:
const Z& Z(size_t index) const
{
// same really-really-really long access
// and checking code as in OP
// ...
return vecZ[index];
}
Z& Z(size_t index)
{
// One line. One ugly, ugly line - but just one line!
return const_cast<Z&>( static_cast<const X&>(*this).Z(index) );
}
#if 0 // A slightly less-ugly version
Z& Z(size_t index)
{
// Two lines -- one cast. This is slightly less ugly but takes an extra line.
const X& constMe = *this;
return const_cast<Z&>( constMe.Z(index) );
}
#endif
};
注意: strong>将逻辑放在非const函数中,并使用const函数调用非const函数 - 它可能导致未定义的行为。原因是常量类实例被转换为非常量实例。非const成员函数可能会意外修改类,C ++标准状态将导致未定义的行为。
NOTE: It is important that you do NOT put the logic in the non-const function and have the const-function call the non-const function -- it may result in undefined behavior. The reason is that a constant class instance gets cast as a non-constant instance. The non-const member function may accidentally modify the class, which the C++ standard states will result in undefined behavior.