考虑一下:
void l(Event const& e)
{
KeyEvent& k = (KeyEvent&)e;
std::cout<<k.action<<" "<<k.keyCode;
}
void k(Event const& e)
{
KeyEvent& k = (KeyEvent&)e;
std::cout<<k.action<<" "<<k.keyCode;
}
void t(Event const& e)
{
l(e);
k(e);
}
int main(int argc, char* argv[])
{
t(KeyEvent(1,1));
}
KeyEvent 对象何时从内存中释放(是在作用域结束之后还是我必须删除它)?如果该 KeyEvent 实际上传递的次数远不止于此,我能否确定它会一直有效,直到最后一个使用它的函数结束?
最佳答案
When will the KeyEvent object be released from memory (is it after the scope ends or do I have to delete it)?
它一直存在于内存中,直到完整表达式的末尾,即语句的分号 ;
:
t(KeyEvent(1,1));
^ end of the full-expression
顺便说一句,你应该在这里const
(以避免问题):
KeyEvent const& k = (KeyEvent const&)e; //added const on both side
关于c++ - C++中的const参数生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360351/