MS VS 2017中由前向引用传递的std :: string文字的空对象?

时间:2019-04-23 10:18:54

标签: c++ visual-studio stdstring

能否请您向我解释一下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;
}

output

1 个答案:

答案 0 :(得分:2)

std::forward<T>(x)是有条件的移动-如果T不是左值引用,则x将被移动。对于a2a3,在打印之前,您的str被移到数据成员text中。在打印时,由于未指定str的状态,所以会发生任何事情。