Address of a temporary in Go?

后端 未结 8 745
不知归路
不知归路 2021-02-01 13:24

What\'s the cleanest way to handle a case such as this:

func a() string {
    /* doesn\'t matter */
}

b *string = &a()

This generates the

8条回答
  •  梦如初夏
    2021-02-01 14:08

    guess you need help from More effective Cpp ;-)

    Temp obj and rvalue

    True temporary objects in C++ are invisible - they don't appear in your source code. They arise whenever a non-heap object is created but not named. Such unnamed objects usually arise in one of two situations: when implicit type conversions are applied to make function calls succeed and when functions return objects.”

    And from Primer Plus

    lvalue is a data object that can be referenced by address through user (named object). Non-lvalues include literal constants (aside from the quoted strings, which are represented by their addresses), expressions with multiple terms, such as (a + b).

    In Go lang, string literal will be converted into StrucType object, which will be a non-addressable temp struct object. In this case, string literal cannot be referenced by address in Go.

    Well, the last but not the least, one exception in go, you can take the address of the composite literal. OMG, what a mess.

提交回复
热议问题