C++ inline function
inline function
在呼叫函數時,會將控制權由caller傳給callee,也會進行一些必要的資源分配,即overhead。
如果這段事前準備的時間比callee的執行時間比還長,那麼呼叫函數明顯就是不划算的。
為了避免這種情況發生,我們可以將函數定義為inline function。如此一來,編譯器便會(選擇性地)將callee的代碼替換到caller中,從而免去了函數呼叫的過程。
以下代碼來自TensorRT/samples/common/logging.h
:
inline LogStreamConsumer LOG_VERBOSE(const Logger& logger)
{
return LogStreamConsumer(logger.getReportableSeverity(), Severity::kVERBOSE);
}
展示了將一個函數定義為inline
的方式。