Reputation: 113
The following code is from Thinking in C++. The author mentioned that "Since operator[] is an inline, you could use this approach to guarantee that no array-bounds violations occur, then remove the require() for the shipping code." What feature of inline function is referred here? Thanks!
#include "../require.h"
#include <iostream>
using namespace std;
template<class T>
class Array {
enum { size = 100 };
T A[size];
public:
T& operator[](int index) {
require(index >= 0 && index < size,
"Index out of range");
return A[index];
}
};
Upvotes: 0
Views: 122
Reputation: 727047
The author refers to the feature of inline
functions to be expanded at the invocation site, as if you wrote their body in place of the invocation. This guarantees no loss of efficiency - not even the tiny one associated with invoking a function on modern hardware. In addition, the compiler could potentially optimize the code better when the indexing operator is expanded inline, because the nature of the code inside the function would be known to the optimizer.
As far as removing the require
from the shipping code goes, you would need to do it manually in the current implementation. You could also use conditional compilation to remove bounds checking in production code.
Upvotes: 1