struct X{ Y y; }; struct do_nothing_deleter{ template<typename> void operator()(T*){} }; void store_for_later(std::shared_ptr<Y>); void foo(){ std::shared_ptr<X> px(std::make_shared<X>()); std::shared_ptr<Y> py(&px->y,do_nothing_deleter()); store_for_later(py); } // our X object is destroyed, BAD!
void bar(){ std::shared_ptr<X> px(std::make_shared<X>()); std::shared_ptr<Y> py(px,&px->y); store_for_later(py); } // our X object is kept alive, i.e px NEVER destroyed even out of scope. struct X2{ std::unique_ptr<Y> y; X2():y(new Y){} }; void baz(){ std::shared_ptr<X2> px(std::make_shared<X2>()); std::shared_ptr<Y> py(px,px->y.get()); store_for_later(py); } // our X2 object is kept alive, DITTOaa as
http://stackoverflow.com/a/27109774/1316609
However, r-reference to prvalue's data member will exist
even the prvalue destructs the internal data member(i.e r-reference make a copy out of it),
same as const T&.
For const T& to a l-value data member, the destruct of internal data member will
effect the outer const T&, this is by standard.
http://stackoverflow.com/a/3097861
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.