以下代码警告我将临时参数作为参数传递给接受引用的函数:
struct TempObject
{
typedef TempObject& reference;
const int First, Second;
TempObject(int first, int second) : First(first), Second(second) {}
};
void Function(const TempObject::reference ref)
{
std::cout<< ref.First << ref.Second;
}
int main(int argc, char *argv[])
{
Function(TempObject(1, 2)); // warning is given here
}
这让我感到困惑,因为Function
实际上是在接受一个const TempObject::reference
. 更改 to 的定义TempObject::reference
会typedef const TempObject& reference
导致编译器不再发出警告。
为什么有区别?我在 Microsoft 和 Intel 的编译器中发现了这种行为。