gpt4 book ai didi

c++ - 为什么我的构造函数允许使用临时对象调用非 const 引用作为参数?

转载 作者:可可西里 更新时间:2023-11-01 18:15:18 26 4
gpt4 key购买 nike

我在下面有一个示例代码。

#include<iostream>

template<typename T>
class XYZ
{
private:
T & ref;
public:
XYZ(T & arg):ref(arg)
{
}
};
class temp
{
int x;
public:
temp():x(34)
{
}
};
template<typename T>
void fun(T & arg)
{
}
int main()
{
XYZ<temp> abc(temp());
fun(temp()); //This is a compilation error in gcc while the above code is perfectly valid.
}

在上面的代码中,即使 XYZ 构造函数将参数作为非 const 引用,它也可以正常编译,而 fun 函数无法编译。这是特定于 g++ 编译器还是 c++ 标准必须对此说明什么?

编辑:

g++ -v 给出了这个。

gcc 版本 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)

最佳答案

 XYZ<temp> abc(temp());

它可以编译,因为它不是变量 声明。我敢肯定您认为它是一个变量声明,而事实是它是一个函数 声明。函数的名称是 abc ;该函数返回类型为 XYZ<temp> 的对象并接受一个(未命名的)参数,该参数又是一个函数返回类型 temp并且不争辩。有关详细说明,请参阅这些主题:

fun(temp())不编译,因为 temp()创建一个临时对象,临时对象不能绑定(bind)到非常量引用。

所以解决方法是:将函数模板定义为:

template<typename T>
void fun(const T & arg) //note the `const`
{
}

关于c++ - 为什么我的构造函数允许使用临时对象调用非 const 引用作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6268228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com