如下代码
submatch foo(...){
if (rc > 0){
submatch sm(Str, ovector,rc);
return sm;
}
else {
return nullptr;
}
然而这个语句不能成立,因为函数返回的签名不是指针,不能用nullptr
但我又不希望用指针,因为用了指针,调用这要负责delete,这是不希望的
我希望C++能和python类似,如果异常返回None,类似nullptr,
调用着也不需要关心delete对象的问题
auto m = foo();
if (m 不是null) {
操作m
}
无需delete m
怪我咯2017-04-17 13:28:13
Since you don’t want to be responsible for the release of resources and want to use the characteristics of pointers, you can only use smart pointers and let the pointers be responsible for the release of resources. Whether to use unique_ptr
or shared_ptr
depends on your needs.
Use unique_ptr
if an object can only be pointed to by a unique pointer, that is, this pointer has ownership of the object it points to.
If an object can be pointed to by multiple pointers, use shared_ptr
.
In other words, the object obtained by allocating dynamic memory is actually a resource, and the pointer is the channel to access this resource. When this resource is an exclusive resource, unique_ptr
is required. When this resource is a shareable resource, use shared_ptr
. unique_ptr
cannot be copied and can only be moved; while shared_ptr
can be copied. Generally, if you can use unique_ptr
, don’t use shared_ptr
.