ecr23xx / C-Study

It's about my C study, including C and Cpp
1 stars 1 forks source link

C++11 learning (2) #12

Open ecr23xx opened 8 years ago

ecr23xx commented 8 years ago

Closure

Variable cannot be implicitly captured in a lambda with no capture-default specified, then sometimes we may need closure.
To explain it, please view codes below

// Print the contents of the vector.  
std::for_each(v.begin(), v.end(), [](int i) { cout << i << " "; });  

[](int i) { cout << i << " "; } is a closure. It's some kind of lambda.
c++11-lambda and closures

Functor

With functor, an object can be used as a function. What you needs is just to overload operator '()'.
Maybe it has some advantages, but i can't understad those advantages...Here I'll give you an example.

class fun {
public:
  fun() { s = 0; }
  fun &operator()(int x) {
    s += x;
    return (*this);
  }
  int get() { return s; }
  int set() { s = 0; }
  friend ostream& operator << (ostream& output, fun& sum) {
    output << sum.get();
    return output;
  }

private:
  int s;
};

int main() {
  fun Sum;
  cout << Sum(2)(3) << endl;
  Sum.set();
  cout << Sum(2)(3)(4) << endl;
}

Smart Pointer

In c++98 we have auto_ptr, but its return value is a lvalue and it can't call delete[]. In c++11, it has been abandoned.

1. unique_ptr

As showed by its name, unique_ptr can't be copied but can be moved.

  unique_ptr<int> up1(new int(11));

  // unique_ptr<int> up2 = up1;
  // can't be copied

  unique_ptr<int> up3 = move(up1);
  // can be moved
  // this line means fill up3 with up1 and clear up1

  // cout << *up1 << endl;
  // up1 is empty, it'll cause memory error

  cout << *up3 << endl;
  up3.reset();  // clear. it doesn't matter if without it
  up1.reset();  // okay
  // cout << *up3 << endl;

2. shared_ptr

One part of memory can be pointed by several pointer, realized by 引用计数 (^v^). When deleted one pointer, the value wont't be destructed if number is bigger than 1. 1

shared_ptr<int> sp1(new int(22));
shared_ptr<int> sp2 = sp1;
cout << *sp1 << endl;  // 22 
cout << *sp2 << endl;  // 22 
sp1.reset();  // didn't free the memory
cout << *sp2 << endl;  // 22