c++ 11 new features

We don’t need to use “new” and “delete” anymore! In c++11, there are smart printers!

Here are some sample code:

struct Base
{
    Base() {}
    ~Base() {}
};
 
struct Derived: public Base
{
    Derived() {}
    ~Derived() {}
};

void main(){
    std::shared_ptr<Base> p = std::make_shared<Derived>();
}

There is another kind of smart pointer called unique pointer. The difference between them is that when using unique_ptr, there can be at most one unique_ptr pointing at any one resource. To move an unique pointer, you can either use return to give it back to the upper level or use move function like following:

unique_ptr<T> myPtr(new T);                  
unique_ptr<T> myOtherPtr = std::move(myPtr);

Simply speaking:

  • Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
  • Use shared_ptr when you want multiple pointers to the same resource.

 

However, try to avoid use shared_ptr, since the system will be confused about when to recycle the pointer and cause waste.

发表评论

电子邮件地址不会被公开。 必填项已用*标注