Commit cbec2f20 authored by Laurent Demailly's avatar Laurent Demailly Committed by Facebook Github Bot

improve documentation of custom singleton creation through an example

Summary:
improve documentation of custom singleton creation through an example
(from fbcode SIOF thread suggestion)

Reviewed By: yfeldblum

Differential Revision: D4053322

fbshipit-source-id: e9c2ef3d1ef43d52c0bf0a601d94c017047a23a3
parent d8d93ebf
...@@ -71,6 +71,15 @@ ...@@ -71,6 +71,15 @@
// Where create and destroy are functions, Singleton<T>::CreateFunc // Where create and destroy are functions, Singleton<T>::CreateFunc
// Singleton<T>::TeardownFunc. // Singleton<T>::TeardownFunc.
// //
// For example, if you need to pass arguments to your class's constructor:
// class X {
// public:
// X(int a1, std::string a2);
// // ...
// }
// Make your singleton like this:
// folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); });
//
// The above examples detail a situation where an expensive singleton is loaded // The above examples detail a situation where an expensive singleton is loaded
// on-demand (thus only if needed). However if there is an expensive singleton // on-demand (thus only if needed). However if there is an expensive singleton
// that will likely be needed, and initialization takes a potentially long time, // that will likely be needed, and initialization takes a potentially long time,
......
...@@ -610,3 +610,25 @@ TEST(Singleton, DoubleRegistrationLogging) { ...@@ -610,3 +610,25 @@ TEST(Singleton, DoubleRegistrationLogging) {
EXPECT_EQ(SIGABRT, res.killSignal()); EXPECT_EQ(SIGABRT, res.killSignal());
EXPECT_THAT(err, testing::StartsWith("Double registration of singletons")); EXPECT_THAT(err, testing::StartsWith("Double registration of singletons"));
} }
// Singleton using a non default constructor test/example:
struct X {
X() : X(-1, "unset") {}
X(int a1, std::string a2) : a1(a1), a2(a2) {
LOG(INFO) << "X(" << a1 << "," << a2 << ")";
}
const int a1;
const std::string a2;
};
folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); });
TEST(Singleton, CustomCreator) {
X x1;
std::shared_ptr<X> x2p = singleton_x.try_get();
EXPECT_NE(nullptr, x2p);
EXPECT_NE(x1.a1, x2p->a1);
EXPECT_NE(x1.a2, x2p->a2);
EXPECT_EQ(42, x2p->a1);
EXPECT_EQ(std::string("foo"), x2p->a2);
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment