此常见问题解答涉及聚合和POD,并涵盖以下材料:
以下代码可以在g ++和Visual C++下通过编译.为什么合法?它看起来不合理,可能会导致隐藏的错误.
int main() {
int i = i;
}
Run Code Online (Sandbox Code Playgroud) 我刚刚意识到这个程序编译并运行(gcc版本4.4.5/Ubuntu):
#include <iostream>
using namespace std;
class Test
{
public:
// copyconstructor
Test(const Test& other);
};
Test::Test(const Test& other)
{
if (this == &other)
cout << "copying myself" << endl;
else
cout << "copying something else" << endl;
}
int main(int argv, char** argc)
{
Test a(a); // compiles, runs and prints "copying myself"
Test *b = new Test(*b); // compiles, runs and prints "copying something else"
}
Run Code Online (Sandbox Code Playgroud)
我想知道为什么这个甚至可以编译.我假设(就像在Java中)参数在调用方法/构造函数之前被评估,所以我怀疑这个案例必须由语言规范中的一些"特殊情况"涵盖?
问题:
编辑1:我刚刚意识到我甚至可以写作 int i = i;
编辑2:即使有-Wall …