能否请您解释一下 MS VS 2017 中带有前向引用的奇怪行为?右值 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
的状态未指定。
关于c++ - 在 MS VS 2017 中通过前向引用传递的 std::string 文字的空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55809023/