C++ 使用auto作为成员函数参数时的不同结果
当运行这两个时,我得到了不同的结果 我在GNU/Linux 4.14.67上 这两种方法都是使用C++ 使用auto作为成员函数参数时的不同结果,c++,c++14,c++17,C++,C++14,C++17,当运行这两个时,我得到了不同的结果 我在GNU/Linux 4.14.67上 这两种方法都是使用g++-std=c++14和c++17运行的,其中带/不带-O0 为什么是我?为什么输出不同 第一个版本是: #include <iostream> #include <algorithm> using namespace std; class foo { public: foo() { } foo(const foo& f) { } foo&
g++-std=c++14
和c++17
运行的,其中带/不带-O0
为什么是我?为什么输出不同
第一个版本是:
#include <iostream>
#include <algorithm>
using namespace std;
class foo {
public:
foo() { }
foo(const foo& f) { }
foo& operator=(const foo& f) {
cout << "foo operator=\n";
val = 888;
// Do something important
return *this;
}
int val;
};
int main() {
foo f1;
foo f2;
f1 = f2;
cout << f1.val << endl;
}
第二个版本(仅将
const foo&
更改为const auto&
):
这:
在C++ 20之前,将不是标准的C++代码。但gcc已经允许了相当长的一段时间,这意味着:
template <typename _T>
foo& operator=(const _T& f);
在第一个示例中,该表达式有一个候选项:您编写的复制赋值运算符。在第二个示例中,有两个候选对象:赋值运算符模板和编译器合成的复制赋值运算符。编译器的是更好的匹配(非模板优于模板),所以它被调用-而不是你的 也许你忘了在op=(…)的末尾写“return*this”?我也这么认为,但这是一个复制粘贴错误。好的捕手不仅是“这个”,而且是“还这个”,“我为什么?”很难说,很有哲理的问题。有人说“我在思考,所以我是(am)”@Swardfish Watchworth:你可能想提到P1141@chris digged out。
#include <iostream>
#include <algorithm>
using namespace std;
class foo {
public:
foo() { }
foo(const foo& f) { }
foo& operator=(const auto& f) {
cout << "foo operator=\n";
val = 888;
// Do something important
return *this;
}
int val;
};
int main() {
foo f1;
foo f2;
f1 = f2;
cout << f1.val << endl;
}
0
foo& operator=(const auto& f);
template <typename _T>
foo& operator=(const _T& f);
f1 = f2;