This is just for fun, it is not in any way an attempt to say that using std::count is bad. But there are still the same types of errors that could occur - name conflicts or unknowingly using the wrong name. Here is my contrived example.Code:// In MyClass.h #ifndef MYCLASS_H_ #define MYCLASS_H_ #include <iostream> using std::cout; using std::endl; #include <algorithm> using std::count; class MyClass { public: MyClass() { sizeOfA = 8; A = new int[sizeOfA]; for (int i=0; i<sizeOfA; i++) A[i] = (i%3)+1; } void PrintItemCount(int item) { cout << item << " count: " << count(A, A + sizeOfA, item) << endl; } private: int* A; int sizeOfA; }; #endif // MYCLASS_H_Code:// In HelperFunc.h #ifndef HELPER_FUNC_H_ #define HELPER_FUNC_H_ int count(int* array1, int* array2, int numElements) { int sum = 0; for (int i = 0; i < numElements; i++) { sum += array1[i]; sum += array2[i]; } return sum; } #endif // HELPER_FUNC_H_Result: undefined behavior - on my machine it crashed. Since HelperFunc.h wasn't included, the code found the std::count included in the MyClass.h header file. Because the using std::count was put in that header file, the main code used the algorithm count instead of the intended one.Code:// In main.cpp // Maybe this header is included by another header deep in a library somewhere. #include "MyClass.h" // Oops! Forgot to #include "HelperFunc.h" #include <iostream> using std::cout; using std::endl; int main() { int array1[] = { 2, 0, 4, 6, 2, 3, 2, -7 }; int array2[] = { 5, 8, 0, 4, 1, 1, -4, 2 }; // Try to use the count in HelperFunc.h cout << count(array1, array2, 8) << endl; }
This is more of an indictment on putting using directives in header files, but there you go.



LinkBack URL
About LinkBacks



