unique_ptr_unittest.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Licensed to the Apache Software Foundation (ASF) under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. The ASF licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing,
  12. // software distributed under the License is distributed on an
  13. // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. // KIND, either express or implied. See the License for the
  15. // specific language governing permissions and limitations
  16. // under the License.
  17. #include <gtest/gtest.h>
  18. #include "butil/unique_ptr.h"
  19. namespace {
  20. class UniquePtrTest : public testing::Test {
  21. protected:
  22. virtual void SetUp() {
  23. };
  24. };
  25. struct Foo {
  26. Foo() : destroyed(false), called_func(false) {}
  27. void destroy() { destroyed = true; }
  28. void func() { called_func = true; }
  29. bool destroyed;
  30. bool called_func;
  31. };
  32. struct FooDeleter {
  33. void operator()(Foo* f) const {
  34. f->destroy();
  35. }
  36. };
  37. TEST_F(UniquePtrTest, basic) {
  38. Foo foo;
  39. ASSERT_FALSE(foo.destroyed);
  40. ASSERT_FALSE(foo.called_func);
  41. {
  42. std::unique_ptr<Foo, FooDeleter> foo_ptr(&foo);
  43. foo_ptr->func();
  44. ASSERT_TRUE(foo.called_func);
  45. }
  46. ASSERT_TRUE(foo.destroyed);
  47. }
  48. static std::unique_ptr<Foo> generate_foo(Foo* foo) {
  49. std::unique_ptr<Foo> foo_ptr(foo);
  50. return foo_ptr;
  51. }
  52. TEST_F(UniquePtrTest, return_unique_ptr) {
  53. Foo* foo = new Foo;
  54. std::unique_ptr<Foo> foo_ptr = generate_foo(foo);
  55. ASSERT_EQ(foo, foo_ptr.get());
  56. }
  57. }