gpt4 book ai didi

c++ - 大括号初始化防止非常量使用临时

转载 作者:IT老高 更新时间:2023-10-28 23:20:52 25 4
gpt4 key购买 nike

我想创建一个 const 对象的临时拷贝并以非常量的方式使用它:

struct S {
S& f() { return *this; }
};

int main() {
const S a{};
S{a}.f(); // Error on this line
return 0;
}

使用 msvc (Visual Studio 2017, C++14),我得到这个错误:

Error C2662 'S &S::f(void)': cannot convert 'this' pointer from 'const S' to 'S &'

如果我将大括号初始化更改为经典初始化,它会起作用:

S{a}.f(); // Does not work
S(a).f(); // Works

这两种变体在 gcc 中都能正常编译。我错过了什么还是这是一个编译器错误?

最佳答案

似乎是另一个 MSVC 错误。

S{a}推导为const struct S,仅此而已。

#include <string>
#include <iostream>

template < class T >
std::string type_name()
{
std::string p = __FUNCSIG__;
return p.substr( 106, p.length() - 106 - 7 );
}


struct S {
S& f() { return *this; }
};

int main() {
const S a{};
//S{a}.f(); // Error on this line
std::cout << type_name<decltype(S{a})>() << std::endl;
return 0;
}

输出:

const struct S

关于c++ - 大括号初始化防止非常量使用临时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43139272/

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