能否请您向我解释一下MS VS 2017中带有前向引用的奇怪行为? rvalue std :: strings(a2&a3)的构造函数获取空字符串。
#include <string>
#include <iostream>
#include <type_traits>
using namespace std;
class A {
string text{};
public:
template <typename T,
typename = typename enable_if_t< !is_base_of_v<A, decay_t<T>> &&
!is_integral_v<remove_reference_t<T>> >>
explicit A(T&& str) : text(forward<T>(str)) {
cout << str << endl;
}
explicit A(int x) : text(to_string(x)) {}
};
int main()
{
string s = "hello"s;
A a1(s);
A a2(" world"s); // why?
A a3(string(" world")); // why?
A a4(" world");
A a5(34);
A a6(a2);
return 0;
}
答案 0 :(得分:2)
std::forward<T>(x)
是有条件的移动-如果T
不是左值引用,则x
将被移动。对于a2
和a3
,在打印之前,您的str
被移到数据成员text
中。在打印时,由于未指定str
的状态,所以会发生任何事情。