c++ - 在 MS VS 2017 中通过前向引用传递的 std::string 文字的空对象?

标签 c++ visual-studio stdstring

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

output

最佳答案

std::forward<T>(x)是有条件的举动 - 如果 T不是左值引用,x将被移动。在a2的情况下和 a3 , 你的 str被移入数据成员 text在打印之前。打印时,任何事情都可能发生,因为 str 的状态未指定。

关于c++ - 在 MS VS 2017 中通过前向引用传递的 std::string 文字的空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55809023/

相关文章:

c++ - 将一串数字解析为整数数组

c++ - VS2010调试器花费了不合理的时间

c++ - 如何通过 Q_PROPERTY 将指向 Q_GADGET 的指针暴露给 QML

c# - 在编译时将文件复制到应用程序文件夹中

.net - Visual Studio 将不必要的 XML doc 文件打包到 WP8 XAP 中

c++ - `=` 分配给新的 std::string 究竟分配了什么?

c++ - 使用模板化基础编译时间类选择器

visual-studio - Visual Studio挂起加载UI库

c++ - C++ 中类似 Python 的字符串乘法

c++ - std::string::empty() const () 不抛出段错误