此代码在 Visual Studio 2017 中引发编译错误:
#include <iostream>
#include <string>
using std::cin;
using std::cout;
template<class T>
class A
{
public:
A(T a);
~A() {}
#if 0
A(const A<T>&);
#else
A(A<T>&);
#endif
T t;
};
template<class T>
A<T>::A(T a) : t(a) {}
template <class T>
#if 0
A<T>::A(const A<T>& a)
#else
A<T>::A(A<T>& a)
#endif
{
t = a.t;
std::cout << "In A copy constructor.\n";
}
int main()
{
std::string s;
A<int> a1(11);
A<double> a2(2.71);
#if 1
A<double> a3 = A<double>(a2); //gives C2440 when copy constructor argument is not const.
//compiler message is: 'initializing': cannot convert from 'A<double>' to 'A<double>'
#else
A<double> a3{a2}; //works when copy constructor argument is not const.
#endif
std::cout << a3.t << "\n";
std::cout << "Press ENTER to exit.\n";
std::getline(std::cin, s);
}
C2440 编译失败:'initializing': cannot convert from 'A<double>' to 'A<double>'.
当前两个#if 0
s 更改为#if 1
s 时(选择带有 const 参数的复制构造函数),程序编译并运行。此外,如果#if 0
为所有条件编译选择,则程序编译并运行。
这个问题对我没有答案。根据 cppreference.com,可以使用非常量参数的复制构造函数:
类 T 的复制构造函数是一个非模板构造函数,它的第一个参数是 T&、 const T&、volatile T& 或 const volatile T&,并且要么没有其他参数,要么其余参数都有默认值。
当我写时,带有非常量参数的复制构造函数无论如何都可以工作
A<double> a3{a2};
那么为什么初始化为
A<double> a3 = A<double>(a2);
当复制构造函数的参数不是 const 时不起作用?
在这种情况下,MSVC 的错误信息尤其缺乏;如果您对此运行 GCC,则会出现以下错误:
main.cpp: In function ‘int main()’:
main.cpp:42:20: error: cannot bind non-const lvalue reference of type ‘A<double>&’ to an rvalue of type ‘A<double>’
42 | A<double> a3 = A<double>(a2); //gives C2440 when copy constructor argument is not const.
| ^~~~~~~~~~~~~
main.cpp:28:15: note: initializing argument 1 of ‘A<T>::A(A<T>&) [with T = double]’
28 | A<T>::A(A<T>& a)
| ~~~~~~^
make: *** [<builtin>: main] Error 1
如果您去掉示例中所有不相关的部分,您将得到:
int main() {
double &a = 2.71;
}
仍然返回相同的错误:
main.cpp: In function ‘int main()’:
main.cpp:2:13: error: cannot bind non-const lvalue reference of type ‘double&’ to an rvalue of type ‘double’
2 | double &a = 2.71;
| ^~~~
make: *** [<builtin>: main] Error 1
要解开它,我们需要查看C++中的不同值类别以及每个类别的限制:
从lvalue
广义上讲,An是有名字的东西。在您最初的失败示例中,lvalue
is 是A<T> &a
复制构造函数的参数,而在我的精简示例中,它是double &a
.
Anrvalue
有点棘手,但它实际上是没有名称的东西。通常它被称为 a temporary
(正如@Eljay 在他们的评论中所做的那样),因为没有名字,它没有生命周期,所以它几乎立即被破坏(有一个警告,如下所述)。在您的示例中,rvalue
是A<double>(a2)
,而在我的示例中是2.71
。
链接的 cppreference 页面有两部分关于rvalue
s 与此处相关:
&int()
,&i++
,&42
,和&std::move(x)
无效第一点是导致复制构造函数出现问题而const
没有传递rvalue
; 的原因。根据语言规则,被引用的对象在构造函数中不再有效。
第二点是允许复制构造函数const
在传递rvalue
;时进行操作。生命周期延长到构造函数内部的引用结束,这允许构造函数复制成员变量等。
您初始化的两种方式a3
与第一种不同:
A<double> a3{a2};
只调用复制构造函数一次,使用lvalue
( a2
) 而第二个:
A<double> a3 = A<double>(a2);
调用复制构造函数两次,第一次使用lvalue
( a2
) 如上所述,第二次使用 an rvalue
(第一次构造函数调用的结果)。但是,复制省略优化将删除其中一个调用,乍一看可能会令人困惑,因为这两个复制构造函数调用中的哪一个导致问题可能并不明显。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句