Why can't I capture this by-reference ('&this') in lambda?

前端 未结 2 492
野性不改
野性不改 2020-11-28 03:10

I understand the correct way to capture this (to modify object properties) in a lambda is as follows:

auto f = [this] () { /* ... */ };
<         


        
2条回答
  •  一整个雨季
    2020-11-28 03:52

    Because standard doesn't have &this in Captures lists:

    N4713 8.4.5.2 Captures:

    lambda-capture:
        capture-default
        capture-list
        capture-default, capture-list
    
    capture-default:
        &
        =
    capture-list:
        capture...opt
        capture-list, capture...opt
    capture:
        simple-capture
        init-capture
    simple-capture:
        identifier
        &identifier
        this
        * this
    init-capture:
        identifier initializer
        &identifier initializer
    
    1. For the purposes of lambda capture, an expression potentially references local entities as follows:

      7.3 A this expression potentially references *this.

    So, standard guarantees this and *this is valid, and &this is invalid. Also, capturing this means capturing *this(which is a lvalue, the object itself) by reference, rather than capturing this pointer by value!

提交回复
热议问题