Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined behavior and temporaries

Tags:

1) Is it undefined behavior to return a reference to a temporary, even if that reference is not used? For example, is this program guaranteed to output "good":

int& func()
{
    int i = 5;
    return i;
}

int main()
{
    func();

    cout << "good" << endl;
    return 0;
}

2) Is it undefined behavior to simply have a reference to an object that no longer exists, even if that reference is not used? For example, is this program guaranteed to output "good":

int main()
{
    int *j = new int();
    int &k = *j;
    delete j;

    cout << "good" << endl;
    return 0;
}

3) Is it undefined behavior to combine these?

int& func()
{
    int i = 5;
    return i;
}

int main()
{
    int& p = func();

    cout << "good" << endl;
    return 0;
}