Fan*_*Fox 5 c++ arrays polymorphism
在更有效的C++中,提出一个有趣的观点是混合数组和多态是一个坏主意.例如:
class Base {
public:
Base(int y) : a(y) {}
int a;
};
class D : public Base {
public:
D(int w, int y) : Base(y), c(w) {}
int c;
};
std::ostream& operator<<(std::ostream& os, const Base &obj )
{
os << obj.a << std::endl;
return os;
}
// This function will work perfectly well if i pass in a `Base` array,
// but if i pass in `D` array we are going to run into some problems.
// Namely that `arr[i+1] = &arr[i] + sizeof(Base)` will not progress
// the array correctly for a `D` array.
void printArray(const Base arr[]) {
for (int i = 0; i < 5; ++i) {
std::cout << arr[i];
}
}
int main() {
D arr[5] = { D(0, 10), D(1, 11), D(2, 12), D(3, 13), D(4, 14)};
printArray(arr); // This compiles without complaint! I understand that the
// conversion is legal, but it seems like a warning
// about this would be a good idea.
}
Run Code Online (Sandbox Code Playgroud)
注意:我知道这是糟糕的设计但是要说明一点.
这里的问题是,当我按照上面的方式混合这两个时,当我们遍历数组进行打印时,我们将不会以正确的数量(即我们移动sizeof(Base)而不是sizeof(D))来推进数组的元素.这导致输出:
10
0
11
1
12
Run Code Online (Sandbox Code Playgroud)
(而且我猜这样称呼operator<<这可能是UB).
在编译时g++ -std=c++1y -Wall -Weffc++ -pedantic main.cpp我没有收到任何警告或错误.