![](/img/trans.png)
[英]When is the memory space for a member function of a class in C++ allocated?
[英]c++ Why is memory allocated when passing a string literal to a function?
我有他的代碼:
int setAttrib(const string& name, int components){
// here I don't even touch 'name'
if(components == 2) return 3;
else return 1;
}
我這樣稱呼 function :
setAttrib("position", 3);
我正在使用 xcode 分析器分析 memory 並在 function 調用 std::string 中進行分配。
這是為什么?
編輯:
避免這種分配的最佳方法是什么? 因為我經常調用function ,並且在大約 10 秒的時間內我最終在該行中分配了大約 10MB。
謝謝。
你要求一個const string&
,但傳入一個const char*
。 因此,編譯器需要創建一個正確類型的臨時 object。
"position"
不是std::string
而是char const*
的事實更像是一個歷史事故(從 C 繼承,當 C++ 中沒有string
class 時)而不是設計決策,但仍然要記住一些事情.
因為std::string
通常分配堆 memory 來保存字符串。 在這種情況下, std::string
是從字符串文字隱式構造的(它本身駐留在 static 存儲中)。 一些字符串實現使用一個小緩沖區來提供小字符串,但這里似乎不是這種情況,並且無論如何都是依賴於實現的。
不使用name
並不重要 - 基本上, setAttrib("position", 3)
是setAttrib(std::string("position"), 3);
的簡寫。 ,所以當控制進入setAttrib
時,memory 已經被分配(當然,在您的隔離代碼示例中,編譯器可以內聯getAttrib
然后完全刪除字符串構造,但這是編譯器優化,而不是語言功能)。
請注意,在 function 調用期間創建的臨時對象在 function 返回時會自動銷毀,因此沒有 memory 泄漏。
為了調用 function 編譯器需要構造所有參數,包括const string& name
,在你的情況下這樣做的唯一方法(你傳遞一個字符串文字)是構造一個臨時std::string
這需要一個堆memory 在大多數實現中的分配。 是否使用 function 中的值都沒有關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.