【发布时间】:2017-08-25 15:24:55
【问题描述】:
我想创建一个 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),我得到这个错误:
错误 C2662 'S &S::f(void)': 无法将 'this' 指针从 'const S' 转换为 'S &'
如果我将大括号初始化更改为经典初始化,它会起作用:
S{a}.f(); // Does not work
S(a).f(); // Works
这两种变体都可以在 gcc 中正常编译。我错过了什么还是这是一个编译器错误?
【问题讨论】:
-
您使用哪个版本的 C++ 来编译您的代码?假设 C++11
-
fyi g++ 5.1.0 编译正常
-
那是MSVC给你的:
-
@Elyasin 我将其编译为 C++14
标签: c++ temporary list-initialization