Skip to content

Instantly share code, notes, and snippets.

// In C++11, the unordered (a.k.a. hashed) containers are standardized.
#include <unordered_map>
std::unordered_map<std::string, size_t> hits_by_url;
++hits_by_url[query.getUrl()];
// C++11 offers type inference. That can cut both ways:
std::vector<std::map<std::string, std::string>> my_vec;
// OUCH:
std::vector<std::map<std::string, std::string>>::iterator current = my_vec.begin();
// Better, but still pretty verbose, and introduces a new name to grok.
typedef std::vector<std::map<std::string, std::string>> strmap_vec;
strmap_vec::iterator current = my_vec.begin();
// C++11 gives us finer control over inheritance:
struct Base {
virtual void doThing() = 0;
};
struct Derived final : public Base {
virtual void doThang() override { // Won't compile, because it doesn't override
}
}
// C++11 has a well defined NULL, now called nullptr, of type nullptr_t:
void f(char *);
void f(int);
foo(NULL); // OOPS: calls f(int)
foo(nullptr); // calls f(char *)
// C++11 removes the silly template angle bracket rules:
std::vector<std::map<std::string, std::string> > // C++03, lame
std::vector<std::map<std::string, std::string>> // C++11, not lame
@acmorrow
acmorrow / gist:4589450
Created January 21, 2013 21:13
Using std::pair to return an error code.
// Promising
std::pair<Status, Foo*> makeAFoo(int param1, int param2);
std::pair<Status, Foo*> result = makeAFoo(42, 0);
if (result.first) {
result.second->doSomething();
} else {
// handle error
}
@acmorrow
acmorrow / gist:4589420
Created January 21, 2013 21:09
error_or: getLastError example
// GetLastError is no better
Foo* makeAFoo(int param1, int param2)
Foo* newFoo = makeAFoo(42, 0);
// Easy to forget to call this...
Status s = getLastError();
if (s) {
newFoo->doSomething();
} else {
// handle Error
}
@acmorrow
acmorrow / gist:4589211
Created January 21, 2013 20:49
error_or: return codes example
// Error handling with return codes
Status makeAFoo(Foo** result, int param1, int param2);
Foo* newFoo = NULL;
Status s = makeAFoo(&result, 42, 0);
if (s) {
// use newFoo
} else {
// handle error
}