Why do some c++ compilers let you take the address of a literal?

后端 未结 5 459
北荒
北荒 2021-01-03 08:08

A C++ compiler that I will not name lets you take the address of a literal, int *p = &42;

Clearly 42 is an r-value and most compilers refuse to do so.

W

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-03 09:01

    Tongue slightly (nut by no means totally) in cheek:

    I'd say that in C++ application code taking the address of an integer whether lvalue or rvalue is almost always a mistake. Even using integers, for doing anything much more than controlling loops or counting is probably a design error, and if you need to pass an integer to a function which might change it, use a reference.

提交回复
热议问题