Why use non-member begin and end functions in C++11?

Every standard container has a begin and end method for returning iterators for that container. However, C++11 has apparently introduced free functions called std::begin and std::end which call the begin and end member functions. So, instead of writing auto i = v.begin(); auto e = v.end(); you’d write auto i = std::begin(v); auto e = … Read more

How is “=default” different from “{}” for default constructor and destructor?

I originally posted this as a question only about destructors, but now I’m adding consideration of the default constructor. Here’s the original question: If I want to give my class a destructor that is virtual, but is otherwise the same as what the compiler would generate, I can use =default: class Widget { public: virtual … Read more

How do I call ::std::make_shared on a class with only protected or private constructors?

I have this code that doesn’t work, but I think the intent is clear: testmakeshared.cpp #include <memory> class A { public: static ::std::shared_ptr<A> create() { return ::std::make_shared<A>(); } protected: A() {} A(const A &) = delete; const A &operator =(const A &) = delete; }; ::std::shared_ptr<A> foo() { return A::create(); } But I get this … Read more

Using generic std::function objects with member functions in one class

For one class I want to store some function pointers to member functions of the same class in one map storing std::function objects. But I fail right at the beginning with this code: #include <functional> class Foo { public: void doSomething() {} void bindFunction() { // ERROR std::function<void(void)> f = &Foo::doSomething; } }; I receive … Read more

make_unique and perfect forwarding

Why is there no std::make_unique function template in the standard C++11 library? I find std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3)); a bit verbose. Wouldn’t the following be much nicer? auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3); This hides the new nicely and only mentions the type once. Anyway, here is my attempt at an implementation of make_unique: … Read more

Is local static variable initialization thread-safe in C++11? [duplicate]

This question already has answers here: Is Meyers’ implementation of the Singleton pattern thread safe? (6 answers) Closed 4 years ago. I know this is an often asked question, but as there are so many variants, I’d like to re-state it, and hopefully have an answer reflecting the current state. Something like Logger& g_logger() { … Read more