C++智能指针使用时遇到的坑
unique_ptr
当函数返回unique_ptr时,会自动使用move拷贝,所以经常会有下面这样类似的用法:
unique_ptr<int> connect() {
unique_ptr<int> p(new int(10));
// to do something
return p;
}
问题在g++编译器中出现,如果有时候忘记了返回unique_ptr,也就是忘记了写return p
这句话,那么g++的编译不会报错。
但是如果在代码中调用了如下语句
unique_ptr<int> p = connect();
那么则直接程序奔溃,也不会有报错提示。
然而MSVC编译器面对上述问题会编译报错,要求显示的返回一个值。