Replace Singleton<T>::get() with Singleton<T>::try_get and make it obsolete
[folly.git] / folly / test / SingletonVaultCTest.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/Singleton.h>
18 #include <folly/SingletonVault_c.h>
19
20 #include <gtest/gtest.h>
21
22 #include <thread>
23
24 __thread long instance_counter_instances = 0;
25
26 class InstanceCounter {
27  public:
28   InstanceCounter() {
29     instance_counter_instances++;
30   }
31
32   ~InstanceCounter() {
33     instance_counter_instances--;
34   }
35 };
36
37 TEST(SingletonVault, singletonReturnsSingletonInstance) {
38   SingletonVault_t *c = SingletonVault_singleton();
39   auto *cpp = folly::SingletonVault::singleton();
40   EXPECT_EQ(c, cpp);
41 }
42
43 struct TestTag {};
44 template <typename T, typename Tag = folly::detail::DefaultTag>
45 using SingletonTest = folly::Singleton <T, Tag, TestTag>;
46
47 TEST(SingletonVault, singletonsAreCreatedAndDestroyed) {
48   auto vault = folly::SingletonVault::singleton<TestTag>();
49   SingletonTest<InstanceCounter> counter_singleton;
50   SingletonVault_registrationComplete((SingletonVault_t*) vault);
51   SingletonTest<InstanceCounter>::try_get();
52   EXPECT_EQ(instance_counter_instances, 1);
53   SingletonVault_destroyInstances((SingletonVault_t*) vault);
54   EXPECT_EQ(instance_counter_instances, 0);
55 }