Recently, while watching the GoingNative conference, I learned about the new std::shared_ptr helper function std::make_shared. In the talk Stephan T. Lavavej discusses the performance improvements they've made. It seems std::make_shared can save a few extra allocations and a bit of memory overhead. This can be significant if you dynamically create lots of objects.
Back in the real world I found myself wondering if boost supported this little gem for boost::shared_ptr. Seems it does. And has since 1.39.0 in 2009. How is it possible that I've overlooked this?
Example usage:
Instead of doing this:
boost::shared_ptr<MyClass> ptr(new MyClass(param1, param2)); std::shared_ptr<MyClass> ptr2(new MyClass(param1, param2));
Do this:
boost::shared_ptr<MyClass> ptr = boost::make_shared<MyCass>(param1, param2); std::shared_ptr<MyClass> ptr2 = std::make_shared<MyClass>(param1, param2);
Where this really shines is if you have a function expecting a shared_ptr.
void somefunc(const std::shared_ptr<MyClass> &ptr); // Instead of this: somefunc(std::shared_ptr<MyClass>(new MyClass(param1, param2))); // do this: somefunc(std::make_shared<MyClass>(param1, param2));
Similar functions exist for the other types of smart pointers.
Related boost docs are here.
Recent comments
38 weeks 2 days ago
38 weeks 6 days ago
38 weeks 6 days ago
38 weeks 6 days ago
38 weeks 6 days ago
39 weeks 1 day ago
50 weeks 1 day ago
1 year 2 days ago
1 year 3 weeks ago
1 year 5 weeks ago