Указатель на безымянную локальную переменную

Рейтинг: 0Ответов: 1Опубликовано: 14.04.2015

Можно ли сделать так? Побьется ли указатель?

void foo()
{
    SomeType *pObj = nullptr;
    pObj = &(SomeType(arg1, arg2));
    ...
    // *pObj ?
}

Ответы

▲ 5Принят

Нельзя. Продлевает срок жизни только константная lvalue-ссылка и rvalue-ссылка. Вот так можно:

void foo()
{
    const SomeType& obj = SomeType(arg1, arg2);
    ...
    // obj !
}

и вот так:

void foo()
{
    SomeType&& obj = SomeType(arg1, arg2);
    ...
    // obj !
}

Доказательство вышесказанного можно найти в стандарте C++(12.2/5):

There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression ....

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except...