铺垫:C++类和对象的原理

Class = data structure + code (methods).
Object = memory allocation + data + virtual functions.

背景

众所周知,C++实例化对象有两种方式

  1. class simple_class {
  2. private:
  3. int val;
  4. public:
  5. simple_class(int val);
  6. int getVal() const;
  7. };
  • 直接调用构造函数

    1. void test_constructor() {
    2. simple_class sp(0xFFFF);
    3. std::cout << "val: " << sp.getVal() << std::endl;
    4. }
  • 通过operate new去申请空间,赋值给一个类指针

    1. void test_ptr() {
    2. simple_class *spp;
    3. spp = new simple_class(0xAAAA);
    4. std::cout << "val: " << spp->getVal() << std::endl;
    5. }

    两种方法的汇编也会有所差距