Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mrdomino
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrdomino/f26d38bed3ea5f4efa2f to your computer and use it in GitHub Desktop.
Save mrdomino/f26d38bed3ea5f4efa2f to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <future>
#include <map>
#include <memory>
#include <string>
void do_thing(std::string a); // forces a copy
void do_thing_ref(std::string& a); // no copy, can mutate a
void do_thing_ptr(std::string* a); // no copy, can obviously mutate a
void do_thing_cref(const std::string& a); // no copy, a is immutable
void do_thing_rref(std::string&& a); // no copy, a is movable
void auto_example() {
struct Foo {
int x;
int y;
std::string z;
};
// braced initializer syntax
auto m = std::map<int, int>{{2, 3}, {4, 5}, {6, 7}};
auto x = Foo{1, 2, "bob"};
decltype(x) y;
// auto, range for loop
// old way:
for (std::map<int, int>::const_iterator it = m.cbegin(); it != m.cend(); ++it) {
printf("%d: %d\n", it->first, it->second);
}
// little better:
for (auto it = m.cbegin(); it != m.cend(); ++it) {
printf("%d: %d\n", it->first, it->second);
}
// fully automatic:
for (auto x : m) {
printf("%d: %d\n", x.first, x.second);
}
}
// dynamic memory management, old, dangerous way:
class HasAResource {
public:
HasAResource() {
a = new int();
}
~HasAResource() {
// do some stuff, maybe throw
delete a;
}
private:
int* a;
};
// dynamic memory management, new, safe way:
class HasAResource11 {
public:
HasAResource11() {
a = std::unique_ptr<int>(new int(5));
// C++14
// a = std::make_unique<int>(5);
}
private:
std::unique_ptr<int> a;
};
// dynamic memory management, shared memory
class SharesAResource {
public:
SharesAResource(std::shared_ptr<int> const& a): a_(a) {}
private:
std::shared_ptr<int> a_;
};
// dynamic memory management, breaking cycles
class Follow;
class Lead {
public:
Lead(std::shared_ptr<Follow> const& f): f_(f) {}
private:
std::shared_ptr<Follow> f_;
};
class Follow {
public:
void set_lead(std::shared_ptr<Lead> lead) { l_ = lead; }
private:
std::weak_ptr<Lead> l_;
};
void ref_cycle_example() {
auto follow = std::make_shared<Follow>();
auto lead = std::make_shared<Lead>(follow);
follow->set_lead(lead);
}
void promise_future_example() {
auto promise = std::promise<int>();
auto producer = std::thread(
[&] {
promise.set_value(42);
});
auto future = promise.get_future();
auto consumer = std::thread(
[&] {
printf("%d\n", future.get());
});
producer.join();
consumer.join();
}
constexpr int is_coprime(int a, int n) {
return a % n == 0;
}
int main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment