[stdex] Introduce Memory.h (#1494)
author박종현/동작제어Lab(SR)/Staff Engineer/삼성전자 <jh1302.park@samsung.com>
Fri, 14 Sep 2018 09:40:30 +0000 (18:40 +0900)
committerGitHub Enterprise <noreply-CODE@samsung.com>
Fri, 14 Sep 2018 09:40:30 +0000 (18:40 +0900)
This commit introduces Memory.h to stdex library, which includes
make_unique implementation (not present in C++ 11).

Signed-off-by: Jonghyun Park <jh1302.park@samsung.com>
contrib/stdex/include/stdex/Memory.h [new file with mode: 0644]
contrib/stdex/src/Memory.test.cpp [new file with mode: 0644]

diff --git a/contrib/stdex/include/stdex/Memory.h b/contrib/stdex/include/stdex/Memory.h
new file mode 100644 (file)
index 0000000..3de992d
--- /dev/null
@@ -0,0 +1,17 @@
+#ifndef __STDEX_MEMORY_H__
+#define __STDEX_MEMORY_H__
+
+#include <memory>
+
+namespace stdex
+{
+
+template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&... args)
+{
+  // NOTE std::make_unique is missing in C++11 standard
+  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+} // namespace stdex
+
+#endif // __STDEX_MEMORY_H__
diff --git a/contrib/stdex/src/Memory.test.cpp b/contrib/stdex/src/Memory.test.cpp
new file mode 100644 (file)
index 0000000..3a95ddd
--- /dev/null
@@ -0,0 +1,44 @@
+#include "stdex/Memory.h"
+
+#include <gtest/gtest.h>
+
+namespace
+{
+
+struct Stat
+{
+  unsigned allocated = 0;
+  unsigned freed = 0;
+};
+
+struct Counter
+{
+public:
+  Counter(Stat *stat) : _stat{stat} { _stat->allocated += 1; }
+
+public:
+  ~Counter() { _stat->freed += 1; }
+
+private:
+  Stat *_stat;
+};
+
+} // namespace
+
+TEST(MemoryTest, make_unique)
+{
+  Stat stat;
+
+  ASSERT_EQ(stat.allocated, 0);
+  ASSERT_EQ(stat.freed, 0);
+
+  auto o = stdex::make_unique<::Counter>(&stat);
+
+  ASSERT_EQ(stat.allocated, 1);
+  ASSERT_EQ(stat.freed, 0);
+
+  o.reset();
+
+  ASSERT_EQ(stat.allocated, 1);
+  ASSERT_EQ(stat.freed, 1);
+}