002 Figuring in C/C++

1. vtable 的基本运作

   编译器不会为所有的类加入vtable,但是每个类只能有一个vtable,所有对象共享一个vtable。

   类中会暗含一个vpinter来指向对应自己的vtable。sizeof(类) == sizeof(对象);

struct Boo {
   int boo;
   virtual int getoo(){ return boo; }
};

struct Foo : Boo {
   int foo;
   int getoo(){ return foo; }
};

int main()
{
   Foo fo;
   Boo* pBo = &fo;
   pBo -> getoo();
   /* it wroks like
   pBo -> vptr -> getoo();
          vpointer points to vtable to get the right virtual function pointer
   */
   return 0;
}

Boo和Foo各自的vpointer,在这里给的是Foo的指针,因此在多态时不会调用错误。虚析构原理亦是如此(顺序从子类到基类)。

2. RAII(Resource Acquisition Is Initialization)

   多用于:多线程编程中的互斥锁;文件读写;智能指针;

   代码拷贝至 Wikipedia

#include <string>
#include <mutex>
#include <iostream>
#include <fstream>
#include <stdexcept>
 
void write_to_file (const std::string & message) {
    // mutex to protect file access
    static std::mutex mutex;
 
    // lock mutex before accessing file
    std::lock_guard<std::mutex> lock(mutex);
 
    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");
 
    // write message to file
    file << message << std::endl;
 
    // file will be closed 1st when leaving scope (regardless of exception)
    // mutex will be unlocked 2nd (from lock destructor) when leaving
    //     scope (regardless of exception)
}

3. Functor 函数子,可带状态的函数

   代码拷贝至 stackoverflow

// this is a functor
struct add_x {
  add_x(int x) : x(x) {}
  int operator()(int y) { return x + y; }

private:
  int x;
};

// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument

std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out;
// Pass a functor to std::transform, which calls the functor on every element 
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1)); 
assert(out[i] == in[i] + 1); // for all i

4. :: 符

template< typename T>
T& max( T& a, T& b )
{
   return a<b ? b:a;
}
::max(1,2); // my max, found in global namespace
std::max(1, 2); // found in std namespace

5. Pointer-to-data-member Type

   code copy from Here

class Car {
public:
    int speed;
};

int main()
{
    int Car::*pSpeed = &Car::speed;
    Car c1;
    c1.speed = 1;       // direct access
    cout << "speed is " << c1.speed << endl;
    c1.*pSpeed = 2;     // access via pointer to member
    cout << "speed is " << c1.speed << endl;
    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2013-03-29 17:32  J.Way.C  阅读(118)  评论(0编辑  收藏  举报