请你在MS VS 2017中用前向引用向我解释一个奇怪的行为吗? r值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;
}
std::forward<T>(x)
是一个有条件的移动 - 如果T
不是左值参考,x
将被移动。在a2
和a3
的情况下,您的str
在打印之前被移动到数据成员text
。打印时,任何事情都可能发生,因为str
的状态未指定。