gpt4 book ai didi

c++ - 将临时对象转换为非常量引用时出错

转载 作者:行者123 更新时间:2023-12-01 21:48:52 28 4
gpt4 key购买 nike

这是一个可重现的示例,取自有关 using temporary stringstream object 的问题:

#include <sstream>                     
#include <string>
#include <iostream>

using namespace std;

std::string transform(std::string);

int main()
{
int i{};
cout << transform( static_cast<stringstream &>(stringstream() << i).str() );
}

当尝试在 MacOS High Sierra 下使用 clang 版本 9.0.0 进行编译时,出现以下错误:

$ clang++ -std=c++11 x.cc -c
x.cc:12:24: error: non-const lvalue reference to type 'basic_stringstream<...>' cannot bind to a temporary of type 'basic_stringstream<...>'
cout << transform( static_cast<stringstream &>(stringstream() << i).str() );
^ ~~~~~~~~~~~~~~~~~~~
1 error generated.

当 g++ 9.2.0 在同一台机器上(也在 Linux 上)使用时,一切都可以正常编译。

似乎将转换从 stringstream & 更改为 const stringstream &stringstream && 可以解决问题。

问题是这是编译器错误还是 clang 对某些标准规则更严格?

最佳答案

是的,我认为这是 libc++ 中的一个错误。

根据[ostream.rvalue]存在过载:

template<class charT, class traits, class T>
basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>&& os, const T& x);

But libc++ implements this similar to :

template <class _Stream, class _Tp>
enable_if_t</*...*/, _Stream&&>
operator<<(_Stream&& __os, const _Tp& __x)
{
// ...
}

该实现使此重载成为比类内 operator<< 更好的候选者的ostream在重载决策中,如果流右值与 << 一起使用,而标准中的签名则不会,并且当它应该返回左值引用时,它也会返回右值引用。它还返回与传递给它的类型相同的引用,同时它应该返回对其 ostream 的引用。基类,根据标准报价。

右值引用无法绑定(bind)到非常量左值引用,因此会出现错误。

该错误已被报告here并且存在关于行为的开放 LWG 问题 here ,这似乎表明将来可能会调整标准以强制 libc++ 当前的行为。

关于c++ - 将临时对象转换为非常量引用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59325270/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com