1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 002 Figuring in C/C++

002 Figuring in C/C++

时间:2021-06-02 17:09:13

相关推荐

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 likepBo -> 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 accessstatic std::mutex mutex;// lock mutex before accessing filestd::lock_guard<std::mutex> lock(mutex);// try to open filestd::ofstream file("example.txt");if (!file.is_open())throw std::runtime_error("unable to open file");// write message to filefile << 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 functorstruct 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 classint i = add42(8); // and "call" itassert(i == 50); // and it added 42 to its argumentstd::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 sequencestd::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 namespacestd::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 accesscout << "speed is " << c1.speed << endl;c1.*pSpeed = 2;// access via pointer to membercout << "speed is " << c1.speed << endl;return 0;}

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。