? 以值的方式对堆内存进行独占管理
? 占用空间大小和裸指针几乎相同,在调用指针函数的时候也和裸指针相同
? 默认情况下,对于内裹指针是通过delete来释放内存的
自己写一个make_unique的
比如make_unique
template <typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args) {
return unique_ptr<T>( new T( std::forward<Args>(args)...));
}
using namespace std;
auto del = [](int* ptr) {
std::cout << "delInstanse is call" << std::endl;
delete ptr;
};
template <typename ...Args>
std::unique_ptr<int, decltype(del)> uniqueFactory(Args&& ...args) {
return unique_ptr<int, decltype(del)> (new int(std::forward<Args>(args)...), del);
}
int main () {
unique_ptr<int, decltype(del)> test(uniqueFactory());
return 0;
}
当然uniqueFactory也可以加一个type参数,实现简单工厂,注意的是我将自定义析构器的类型指定为unique_ptr的第二个类型参数
1. unique_ptr的构造必须括号形式,不可以使用隐士,因为内部是explicit修饰的
2. 当出现unique_ptr<父类> = new 子类的时候,需要保证父类的析构函数是virtual的
3. 可以使用 unique_ptr 直接无缝 工厂/移动语义的方式赋值给shared_ptr,这也是为什么工厂函数使用unique_ptr是合适的
? 本意就是想独占所有权,并且在需要的时候进行内部转移
? auto_ptr使用将原来对象销毁置空的操作,而unique_ptr完全使用移动语义完美实现这一功能,还保证指针的独占性
? auto_ptr无法使用容器包裹,unique_ptr使用移动构造完整这一目的
原文:https://www.cnblogs.com/chaohacker/p/14866439.html