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

问题描述 投票:1回答:1

请你在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;
}

output

c++ visual-studio stdstring
1个回答
2
投票

std::forward<T>(x)是一个有条件的移动 - 如果T不是左值参考,x将被移动。在a2a3的情况下,您的str在打印之前被移动到数据成员text。打印时,任何事情都可能发生,因为str的状态未指定。

© www.soinside.com 2019 - 2024. All rights reserved.