Skip to content

Commit

Permalink
Merge pull request #19 from kenluobo/add_unique_ptr_test_case
Browse files Browse the repository at this point in the history
Add unique ptr test case
  • Loading branch information
kenluobo authored Nov 23, 2024
2 parents c9f44f5 + b8e7306 commit ceb0e57
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions cplusplus/stl/12_concept.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ void test_derived_from() {
std::cout << std::boolalpha;
out(std::derived_from<decltype(d), decltype(b)> == true);


print_base_and_derived_class(b,d);
print_base_and_derived_class(d,b);
}
Expand Down
53 changes: 53 additions & 0 deletions cplusplus/stl/13_unique_ptr.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include "stl.h"
#include "test.hpp"

//====================================================
class Base {
public:
Base() { OUT_FUNC_INFO(); }
Base(const Base &b) { OUT_FUNC_INFO(); }
Base(const Base &&b) { OUT_FUNC_INFO(); }
Base operator=(const Base *b) {
OUT_FUNC_INFO();
return *b;
}
virtual ~Base() { OUT_FUNC_INFO(); }

public:
virtual void out_msg() { out("call ", 1); }
};

class Derived : public Base {
public:
Derived() { OUT_FUNC_INFO(); }
virtual ~Derived() { OUT_FUNC_INFO(); }

public:
virtual void out_msg() override { out("call ", 2); }
};

//====================================================
void test_unique_ptr_1() {
std::unique_ptr<Base> p_b1(new Base());
std::unique_ptr<Base> p_b2 = std::make_unique<Base>();
std::unique_ptr<Base> p_b3 = std::move(p_b2);
std::unique_ptr<Base> p_b4 = std::make_unique<Base>(*p_b3);
}

void test_unique_ptr_2() {
std::unique_ptr<Base> p_b1 = std::make_unique<Derived>();
p_b1->out_msg(); // Derived::otu_msg
p_b1.get()->out_msg(); // Derived::out_msg
static_cast<Base *>(p_b1.get())->out_msg(); // Derived::out_msg

p_b1->Base::out_msg(); // Base::out_msg
}

//====================================================
void test() {
TEST(test_unique_ptr_1);
TEST(test_unique_ptr_2);
}

//====================================================
int main() { test(); }
1 change: 1 addition & 0 deletions cplusplus/stl/utils/stl.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <algorithm>
#include <concepts>
#include <initializer_list>
#include <memory>
#include <string>
#include <type_traits>
#include <typeinfo>
Expand Down
6 changes: 6 additions & 0 deletions cplusplus/stl/utils/test.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,9 @@
template <typename... Args> void out(Args... args) {
(std::cout << ... << args) << "\n";
}

#define OUT_FUNC_INFO(...) \
do { \
out("Current Func: ", __PRETTY_FUNCTION__, " ", \
CONNECT_STRING(__VA_ARGS__)); \
} while (0);

0 comments on commit ceb0e57

Please sign in to comment.