Skip to content

Instantly share code, notes, and snippets.

@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
}
@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: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
}
// 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
// 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 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 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();
// 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 a built-in "owning" pointer which allows transfer of ownership
// and manages lifetime but disallows copying. There is no runtime overhead for its use:
std::unique_ptr<socket> connect_to(const std::string& host, int port) {
/// ...
return new socket(fd);
}
{
auto connected = connect_to("www.10gen.com", 80);
// In C++11, we can ask for the size of a type for which we don't have an instance:
class Tcp6Socket {
public:
struct SockAddr { ... };
};
char buf[1024];
static_assert(sizeof(buf) >= sizeof(Tcp6Socket::SockAddr));
// Can't do that in C++03, but it works in C++11