是下面的代碼安全(它在DEBUG):問題有關的臨時破壞的確切時間C++
void takesPointer(const Type* v);//this function does read from v, it doesn't alter v in any way
Type getValue();
...
takesPointer(&getValue());//gives warning while compiling "not an lvalue"
...
Type tmp = getValue();
takesPointer(&tmp);//this is safe, and maybe I should just do it, instead of posting here
如此 - 它是安全的嗎?我應該忘記它,並使用明確的tmp代碼?
但反正 - 我仍然有興趣,如果優化器能夠從這個調用返回到前殺死臨時:
takePointer(&getValue())
編輯: 謝謝大家! 不幸的是我不能改變函數「takesPointer」(它是一個庫的一部分),我只能將它包裝在一個函數「takesReference」中,它調用takesPointer函數 - 是否會消除副本,還是允許編譯器創建一個副本(「Type」是一個int-3x3-Matrix,所以它不會那麼糟糕,但仍然...)?
inline void takesReference(const Type& v){ takesPointer(&v); }
關於銷燬時間:它會在「takePointer」RETURNS後還是在它被調用之後被銷燬?
'Type'對象將在包含'takesReference'的表達式完成後被銷燬。 – 2015-01-29 01:43:03