At my company I came across the following 2 code snippets, which I found thoroughly unpleasant at first sight, but in the spirit of offering constructive feedback to the engineer who wrote that, I'm trying to come up with technical arguments why this code is bad:
FileTableEntry * FilerManager::GetFileTableEntry(uint32_t i) const {
return &(GetFileTable()[i]);
}
…
for (uint32_t i = 0; i < container_.size(); ++i) {
*GetFileTableEntry(i) = FileTableEntry();
// GetFileTableEntry ultimately accesses a std::vector in FileManager
}
My main arguments are :
Are there other arguments for not writing code like this that I would be missing??
Another argument against this code is that the signature of GetFileTableEntry
returns a pointer in situations when the object is always present. This calls for a reference, not a pointer:
FileTableEntry& FilerManager::GetFileTableEntry(uint32_t i) const {
return GetFileTable()[i];
}
This should address your first point. Your second point can be addressed by making the reference const
:
const FileTableEntry& FilerManager::GetFileTableEntry(uint32_t i) const {
return GetFileTable()[i];
}
This prohibits the callers from modifying the internal state returned by GetFileTableEntry
.
Note: To make the GetFileTableEntry
function useful, one should add a bounds check of the index passed in to catch errors early.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.