32 auto uptr = std::make_unique<int>(10);
34 auto sptr = std::make_shared<int>(100);
46 using element_t = std::tuple<int, std::string>;
48 using uptr_t = std::unique_ptr<element_t>;
49 using container_t = std::vector<uptr_t>;
53 container_t uptr_container; uptr_container.reserve(size);
55 for(
size_t i = 0; i < size; ++i)
58 os <<
"Good Man + " << i ;
61 uptr_container.emplace_back( std::make_unique<element_t>( std::move(t) ) );
69 auto uptr = std::make_unique<int>(10);
73 auto sptr = std::shared_ptr<int>( uptr.release() );
79 stream <<
"Uptr is still valid... it's wrong " <<
endl;
97 if(sptr.use_count()==1)
101 uptr = std::make_unique<int>( *sptr );
107 stream <<
"Now uptr is reconstructed: " << uptr <<
endl;
116 stream <<
"Wow, sptr is still valid: " << sptr <<
endl;
120 stream <<
"Of course, sptr should be invalid" <<
endl;
125template<
typename ElementType>
129 using uptr_t = std::unique_ptr<ElementType>;
130 using sptr_t = std::shared_ptr<ElementType>;
138 m_ptr { std::make_unique<ElementType>(value) } { }
148 if(
this != std::addressof(rhs))
150 this->m_ptr = std::move(rhs.m_ptr);
159 if(
auto ptr = std::get_if<uptr_t>(&this->m_ptr))
167 if(
auto ptr = std::get_if<sptr_t>(&this->m_ptr))
175 if(
auto uptr = std::get_if<uptr_t>(&this->m_ptr))
177 else if(
auto sptr = std::get_if<sptr_t>(&this->m_ptr))
185 if(
auto uptr = std::get_if<uptr_t>(&this->m_ptr))
192 else if(
auto sptr = std::get_if<sptr_t>(&this->m_ptr))
205 if(
auto sptr = std::get_if<sptr_t>(&this->m_ptr))
207 else if(
auto uptr = std::get_if<uptr_t>(&this->m_ptr))
210 this->m_ptr =
sptr_t(uptr->release());
219 if(
auto uptr = std::get_if<uptr_t>(&this->m_ptr))
221 else if(
auto sptr = std::get_if<sptr_t>(&this->m_ptr))
226 auto uptr = std::make_unique<ElementType>(**sptr);
229 this->m_ptr = std::move(uptr);
250 stream <<
"sp.is_unique_ptr()? " << sp.is_unique_ptr() <<
endl;
254 stream <<
"sp.is_shared_ptr()? " << sp.is_shared_ptr() <<
endl;
256 stream <<
"sp.is_unique_ptr()? " << sp.is_unique_ptr() <<
endl;
258 if(sp.is_shared_ptr())
269 stream <<
"The value of sp now ? " << sp <<
endl;
273 stream <<
"Restored back from shared_ptr: " << sp <<
endl;
void why_operator_overloading_for_unique_ptr_and_shared_ptr()
void test_unique_ptr_and_shared_ptr_output()
void test_convert_unique_ptr_to_shared_ptr()
smarter_ptr & to_unique_ptr()
smarter_ptr & operator=(smarter_ptr &&rhs)
std::unique_ptr< ElementType > uptr_t
std::variant< uptr_t, sptr_t > usptr_t
smarter_ptr(const smarter_ptr &)=delete
smarter_ptr(smarter_ptr &&rhs)
smarter_ptr & operator=(const smarter_ptr &)=delete
friend tpf::sstream & operator<<(tpf::sstream &os, const smarter_ptr &sp)
std::shared_ptr< ElementType > sptr_t
smarter_ptr(ElementType value=ElementType{})
smarter_ptr & to_shared_ptr()
Stream output operators << are implemented.