右值对象返回引用较危险
解决方法:ref-qualified
const std::string& getName() const & { return m_name; } // & qualifier overloads function to match only lvalue implicit objects, returns by reference
std::string getName() const && { return m_name; } // && qualifier overloads function to match only rvalue implicit objects, returns by value似乎如果只有const &存在的情况下,左右值对象都会被匹配
这一特性不推荐使用
shared_ptr
int main()
{
Resource* res { new Resource };
std::shared_ptr<Resource> ptr1 { res };
{
std::shared_ptr<Resource> ptr2 { res }; // create ptr2 directly from res (instead of ptr1)
std::cout << "Killing one shared pointer\n";
} // ptr2 goes out of scope here, and the allocated Resource is destroyed
std::cout << "Killing another shared pointer\n";
return 0;
} // ptr1 goes out of scope here, and the allocated Resource is destroyed againmake_shared相比手动构造,可以把对象的所需内存和控制块的内存一起分配,更高效异常安全?
weak_ptr不参与shared_ptr的引用计数(observer),但是能访问到控制块计数,因此相比裸指针,weak_ptr有能力判断对象是否存在
控制块中似乎也有weak计数,不然我感觉shared全部销毁之后,控制块也会销毁,weak_ptr没法判断控制块的存活