Luke B.
Luke B.

Reputation: 1288

const parameter lifespan in c++

Consider this:

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));
}

When will the KeyEvent object be released from memory (is it after the scope ends or do I have to delete it)? And if that KeyEvent was actually passed around a lot more than that, can I be sure it will stay valid until the last function using it ends?

Upvotes: 0

Views: 163

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

When will the KeyEvent object be released from memory (is it after the scope ends or do I have to delete it)?

It lives in the memory till the end of the full-expression which is the semicolon ; of the statement:

t(KeyEvent(1,1));
                ^ end of the full-expression

By the way, you should const here (to avoid problem):

KeyEvent const& k = (KeyEvent const&)e; //added const on both side

Upvotes: 4

Related Questions