当前位置:  开发笔记 > 编程语言 > 正文

std :: move of string literal - 哪个编译器正确?

如何解决《std::moveofstringliteral-哪个编译器正确?》经验,为你挑选了1个好方法。

给出以下代码:

#include 
void foo()
{
  std::string s(std::move(""));
}

这与apple clang(xcode 7)编译,而不是与visual studio 2015生成以下错误:

error C2440: 'return': cannot convert from 'const char [1]' to 'const char (&&)[1]'
note: You cannot bind an lvalue to an rvalue reference
main.cpp(4): note: see reference to function template instantiation 'const char (&&std::move(_Ty) noexcept)[1]' being compiled
    with
    [
        _Ty=const char (&)[1]
    ]

暂时忽略移动是多余的,在这种情况下哪个标准库实现更正确?

我的感觉是该类型即""const char[1]如此std::move应该返回std::remove_reference::type&&这将是const char[1]&&.

在我看来,这应该衰败const char*.

或者我是否误解了这些规则?



1> Shafik Yaghm..:

这看起来像Visual Studio错误.这归结为std :: move,如果我们查看cppreference页面,它具有以下签名:

template< class T >
typename std::remove_reference::type&& move( T&& t );

它返回:

static_cast::type&&>(t) 

这与草案C++标准部分20.2.4前进/移动助手[前进] 相匹配.

使用我从这里抓取的代码,我们可以看到以下示例:

#include 

template
struct value_category {
    // Or can be an integral or enum value
    static constexpr auto value = "prvalue";
};

template
struct value_category {
    static constexpr auto value = "lvalue";
};

template
struct value_category {
    static constexpr auto value = "xvalue";
};

// Double parens for ensuring we inspect an expression,
// not an entity
#define VALUE_CATEGORY(expr) value_category::value


int main()
{   
    std::cout << VALUE_CATEGORY( static_cast::type&&>("") ) << std::endl ;

}

使用Wandbox从gcc和clang生成以下答案:

xvalue

以及使用webcompiler从Visual Studio获得的答案:

lvalue

因此Visual Studio对原始代码的错误:

您不能将左值绑定到右值引用

当它试图绑定结果时static_cast::type&&>(t),std::remove_reference::type&&返回值为std::move.

我没有看到为什么static_cast应该像在Visual Studio案例中那样生成左值的原因.

推荐阅读
雨天是最美
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有