Last active
July 8, 2018 08:50
-
-
Save ifukazoo/45c9e2646d6c27d4be945da7e25f2e09 to your computer and use it in GitHub Desktop.
unique_ptr sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
class A { | |
public: | |
explicit A() { std::cout << __func__ << std::endl; } | |
~A() { std::cout << __func__ << std::endl; } | |
virtual void print() { std::cout << this << std::endl; } | |
}; | |
class B : public A { | |
public: | |
explicit B() { std::cout << __func__ << std::endl; } | |
virtual ~B() { std::cout << __func__ << std::endl; } | |
void print() override { std::cout << "B:" << this << std::endl; } | |
}; | |
int main(int argc, char const* argv[]) { | |
// unique_ptr | |
{ | |
// C++11 | |
auto a = std::unique_ptr<A>(new A()); | |
} | |
{ | |
// C++14 | |
auto a = std::make_unique<A>(); | |
} | |
{ | |
// 所有権の移動 | |
auto a = std::make_unique<A>(); | |
a->print(); | |
auto _a = std::move(a); | |
_a->print(); | |
} | |
{ | |
// 配列 | |
auto a = std::unique_ptr<A[]>(new A[5]); | |
auto integers = std::unique_ptr<int[]>(new int[3]); | |
for (int i = 0; i < 3; i++) { | |
std::cout << integers[i] << std::endl; | |
} | |
// これはできない. | |
// for (int* p = &integers[0]; p < integers + 3; p++) { | |
// std::cout << *p << std::endl; | |
// } | |
} | |
{ | |
// デリファレンス | |
auto a = std::unique_ptr<A>(new A()); | |
(*a).print(); | |
} | |
{ | |
auto b = std::make_unique<B>(); | |
b->print(); | |
} | |
// shared_ptr | |
std::shared_ptr<A> b; | |
{ | |
// C++14 | |
auto a = std::make_shared<A>(); | |
b = a; | |
a->print(); | |
} | |
// まだ開放されていない. | |
b->print(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment