Re:C++11 and Boost - Succinct like Python
by evincarofautumn on Wednesday October 31, 2012 @02:36PM
(#4724389)
“C++11 idioms” include a preference for immutability, which leads to natural factorings. You don’t have to worry about things like iterator invalidation that way.
Also, Haskell is only so safe—at work we’ve taken to rejecting non-total functions in review, because they cause more hassle than they’re worth. By non-total, I refer more to “error” than non-termination, of course.
[ Parent
| on HN ]
Re:C++11 and Boost - Succinct like Python
by pcwalton on Wednesday October 31, 2012 @02:46PM
(#4724421)
"const" doesn't help you in the presence of aliasing:
#include <iostream>
#include <vector>
template<typename T,typename U>
void print(const T& v, U& w) {
for (auto ii = v.begin(), ie = v.end(); ii != ie; ++ii) {
w.clear();
std::cout << *ii << std::endl;
}
}
int main() {
std::vector<std::string> v;
v.push_back(std::string("Hello"));
v.push_back(std::string("there"));
print(v, v);
return 0;
}
In general there are lots of ways to get non-const access to const data. You'd need a sophisticated form of whole-program alias analysis to eliminate the unsafety here. (Even if you didn't have the second "U& w" parameter, there are other potential ways that "print" could get non-const access to "v"; global variables, TLS, by accessing a member of "v", etc.)
Re:C++11 and Boost - Succinct like Python
by ryanmolden on Wednesday October 31, 2012 @05:18PM
(#4724955)
I don't disagree about aliasing, but a print function shouldn't be taking ref to a non-const anything anyways, it should have no need to mutate the vector. You can't clear through a ref to const. Your general point holds but I would say I have probably written/found very few aliasing bugs in C++ over the years, it just doesn't seem to arise often, perhaps your experience differs. Alas there are few ways to prevent dedicated folks from writing really ill-advised code.
Re:C++11 and Boost - Succinct like Python
by evincarofautumn on Wednesday October 31, 2012 @05:21PM
(#4724965)
I see what you’re getting at. Still, if you do the sensible things—immutability, encapsulation of shared state, &c.—then you’re most of the way to safety. I would that C++ made it easier, though; that’s the real issue.