请考虑以下代码:
#include <iostream>
#include <functional>
int main() {
auto run = [](auto&& f, auto&& arg) {
f(std::forward<decltype(arg)>(arg));
};
auto foo = [](int &x) {};
int var;
auto run_foo = std::bind(run, foo, var);
run_foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用clang编译时出现以下编译错误:
$ clang++ -std=c++14 my_test.cpp
my_test.cpp:6:9: error: no matching function for call to object of type 'const (lambda at my_test.cpp:8:16)'
f(std::forward<decltype(arg)>(arg));
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/6.3.1/../../../../include/c++/6.3.1/functional:998:14: note: in instantiation of function template specialization 'main()::(anonymous class)::operator()<const (lambda at my_test.cpp:8:16) &, const int &>' requested here
= decltype( std::declval<typename …Run Code Online (Sandbox Code Playgroud) 当我在MS VS C++ 2010上运行此代码时:
#include <iostream>
int main() {
const int a = 10;
const int *b = &a;
int *c = (int *)b;
*c = 10000;
std::cout << c << " " << &a << std::endl;
std::cout << *c << " " << a << " " << *(&a) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0037F784 0037F784
10000 10 10
Run Code Online (Sandbox Code Playgroud)
编写该代码的动机是Stroustrup的"C++编程语言"中的这句话:"可以通过显式类型转换显式地删除对const指针的限制".
我知道尝试修改常量在概念上是错误的,但我觉得这个结果很奇怪.任何人都能解释其背后的原因吗?