SlideShare a Scribd company logo
Mysterious c++
  Traps, Pitfalls and Secrets



                          Kent Wang
                          Jun 1, 2012
Why this talk

• 警惕靠巧合编程

• 勿在浮沙筑高台

• 了若指掌方可收放自如

• 见山非山, 见水非水
C++很____
C++很____
简单
C++很____
猜猜我是谁

Foo<T> bar;
猜猜我是谁

Foo<T> bar;

template <typename T>
class Foo {
  ...
};
猜猜我是谁

Foo<T> bar;

template <int T>
class Foo {
  ...
};
猜猜我是谁

Foo<T> bar;


int Foo;
int T;
int bar;
仇者联盟大战超人

Foo<T> bar;


Superman Foo;
Spiderman T;
Ironman bar;
sizeof

class A {   class B {    class C {
};             char c;      virtual void foo();
            };              char c;
                         };
sizeof

class A {       class B {    class C {
};                 char c;      virtual void foo();
                };              char c;
                             };


            1
sizeof

class A {       class B {        class C {
};                 char c;          virtual void foo();
                };                  char c;
                                 };


            1                4
sizeof

class A {       class B {        class C {
};                 char c;          virtual void foo();
                };                  char c;
                                 };


            1                4                  8
Constructor
class Animal {
 public:
   Animal() {
     Animal("Lion", 21);
     Run();
   }

     Animal(const string& name, int age);

     virtual void Run() = 0;
};
Constructor
class Animal {
 public:
   Animal() {
     Animal("Lion", 21);
     Run();
   }

     Animal(const string& name, int age);

     virtual void Run() = 0;
};
颤抖吧! 地球人!
简单
C++很____
C++很____
C++很____
恐怖
C++很____
Function Object


       Member Function pointer                      Temporal Object                       dynamic_cast


 Function pointer
                                  Pass By Reference                Pure Virtual Class       RTTI
                                                                                                   typeid

                    Overloading         Pass By Value                  Pure Virtual Function

Copy Constructor
                              Virtual Function                           Multiple Inheritance
                    Constructor                  Dynamic Binding

                                                                      Inheritance
   Exception
         Destructor
                                  Class                                      Virtual Inheritance
                                                                                                   Friend




                                                          Template
                                              String
                              Adaptor
Namespace
                                    STL
   Operator New       RAII               Iterator      Function Template                    Class Template

                                                               Template Specialization
        Memory Management
                                                          Partial Specialization

 Smart Pointer
                            Reference                  Preprocessor
                                                                           Template Meta Programming
知乎?
•   构造和析构函数机制是如何实现的?

•   函数调用是如何传递及返回对象的?

•   函数重载是如何实现的?

•   多态是如何实现的?

•    常机制是如何实现的?为何我们不用?

•   静态变量是如何初始化的?
Tips 1


           Don't live with
         unknown unknowns
What to talk

• C++语言演化历史

• Object Memory Layout

• 函数调用语义及临时对象

• 静态变量初始化
What NOT to talk
• 语法细节

• 二进制兼容性

• Exception Handling

• Template & Generic Programming

• C++11 (C++0x)
Outline
•   青梅煮酒论英雄

•   天机亦可泄露

    -   对象内存模型

    -   函数转换

    -   函数调用

    -   临时对象
青梅煮酒论英雄
Timeline
                                                            2011
   1980                1989                                 C++11
C with class         CFront 2.0              1992
                                             HP C++    Lambda Expression
   Class        Multiple Inheritance                    Automatic Type
Inheritance       Abstract Class           Exception      Threading




                1983 - 1986              1991             1996
               C++ - CFront 1.1        CFront 3.0       C++ 98/03

               Virtual Function        Template          STL
                  Overloading                          Namespace
                   Reference
C++看起来像是...
C++看起来像是...
缘起

               值语义
零负担



        C兼容性


                惯用法
 编译器隐
 藏操作
C兼容性
• class Foo{};

  - unnamed structure in C

• Header File

• Preprocessor / macros
C兼容性
• class Foo{};

  - unnamed structure in C   struct {
                                int a;
                                int b
• Header File                } foo;

                             foo.a = 10;
• Preprocessor / macros
零负担

• 不对栈变量自动初始化

• Object on Stack

• 默认构造函数不对POD类型进行初始化

• 成员函数默认为非虚函数
值语义

Person kent("kent");

                             kent   "kent"
值语义

Person kent("kent");
Person lazy = kent;      kent       "kent"



                             lazy   "kent"
引用语义

Person kent("kent");

                          kent   "kent"
引用语义

Person kent("kent");
Person lazy = kent;       kent
                                 "kent"
                          lazy
Not very good at OO


• No reflection and dynamic creation

• Object lifetime management

• Complex syntax stops refactoring tools
既然如此,
为什么我们还要用C++
C++ is deterministic
C++ is deterministic
• Destructing is determinate

  - No GC

• Performance is predictable

  - C++ is fast only when coders are experts

  - Java is almost as fast, much higher
    productivity
Where the Focus Is
           Efficiency    Flexibility   Abstraction   Productivity



   C                                   non-goal      non-goal



 C++                                                 non-goal



             at the       at the
Java, C#
           expense of   expense of
Conclusion
• There are only two kinds of languages

  - The ones people always complain about

  - The ones nobody uses

• C++ is an undoubted success

• One language doesn’t fit all

  - Important to known when and when not
天机亦可泄漏
对象内存模型
简单对象

class Animal {
 public:
   void Run();

  private:
   char* name;
   int age;
   char sex;
};
简单对象

class Animal {                name
 public:
   void Run();

  private:                    age
   char* name;
   int age;
   char sex;
};                      Sex    Alignment
单一继承
class Animal {
 public:
   void Run();

  private:
   char* name;
   int age;
   char sex;
};

class Lion : public Animal {
  private:
   char* address;
};
单一继承
class Animal {                       address
 public:
   void Run();

  private:                            name
   char* name;
   int age;
   char sex;
};                                    age

class Lion : public Animal {
  private:
   char* address;              Sex     Alignment
};
虚函数

   class Animal {
    public:
      void Run();
      virtual void Say();

     private:
      char* name;
      int age;
      char sex;
   };


* vptr的偏移量与编译器实现有       .
虚函数

   class Animal {                       vptr
    public:
      void Run();
      virtual void Say();               name

     private:
      char* name;                       age
      int age;
      char sex;
   };                             Sex    Alignment


* vptr的偏移量与编译器实现有       .
vptr and vtbl

      vptr


      name


      age


Sex    Alignment
vptr and vtbl

      vptr         0   type_info    type_info


      name         1     Say       &Animal::Say


      age


Sex    Alignment


                   vtbl$Animal
带虚函数的继承
class Animal {
 public:
   virtual void Run();
   virtual void Say();

  private:
   char* name;
   int age;
   char sex;
};

class Lion {
  public:
   virtual void Say();
};
带虚函数的继承
class Animal {
 public:
   virtual void Run();
   virtual void Say();         vptr

  private:
                               name
   char* name;
   int age;
   char sex;
                               age
};

class Lion {             Sex    Alignment
  public:
   virtual void Say();
};
vptr and vtbl

      vptr


      name


      age


Sex    Alignment
vptr and vtbl

      vptr         0    type_info    type_info


      name         1      Run       &Animal::Run


      age          2      Say        &Lion::Say


Sex    Alignment


                       vtbl$Lion
M o re
• 多重继承

• 带虚函数的多重继承

• 虚继承

• 带虚函数的虚继承

• 多重虚继承
函数转换

 class Animal {
  public:
    void Run();

   private:
    ...
 };

 Animal a;
 a.Run();



* 真实情况下编译器会对函数名称进行编码,即name mangling.
函数转换

 class Animal {
  public:
    void Run();

   private:
    ...
 };

 Animal a;
 a.Run();



* 真实情况下编译器会对函数名称进行编码,即name mangling.
函数转换

 class Animal {                    void Animal_Run(Animal* this)
  public:                          {
    void Run();                      ...
                                   }
   private:
    ...                            Animal a;
 };                                Animal_Run(&a);

 Animal a;
 a.Run();



* 真实情况下编译器会对函数名称进行编码,即name mangling.
函数转换

 class Animal {                    void Animal_Run(Animal* this)
  public:                          {
    void Run();                      ...
                                   }
   private:
    ...                            Animal a;
 };                                Animal_Run(&a);

 Animal a;
 a.Run();



* 真实情况下编译器会对函数名称进行编码,即name mangling.
虚函数转换
class Animal {
 public:
   void Run();
   virtual void Say();

  private:
   ...
};

Animal a;
a.Say();

Animal* p = &a;
p->Say();
虚函数转换
class Animal {              void Animal_ctor(Animal* this)
 public:                    {
   void Run();                this.vptr = &Animal_vtbl;
   virtual void Say();      }

  private:                  void Animal_Say(Animal* this)
   ...                      {
};                          }

Animal a;                   Animal a;
a.Say();                    Animal_ctor(&a);
                            Animal_Say(&a);
Animal* p = &a;             Animal* p = &a;
p->Say();                   (*(p->vptr[1]))(p);
虚函数转换
class Animal {              void Animal_ctor(Animal* this)
 public:                    {
   void Run();                this.vptr = &Animal_vtbl;
   virtual void Say();      }

  private:                  void Animal_Say(Animal* this)
   ...                      {
};                          }

Animal a;                   Animal a;
a.Say();                    Animal_ctor(&a);
                            Animal_Say(&a);
Animal* p = &a;             Animal* p = &a;
p->Say();                   (*(p->vptr[1]))(p);
函数调用
• 对象类型参数传递

• 对象类型参数返回

• 临时对象

• Return Value Optimization
简单类型函数调用
int sum(int a, int b) {
   int result = a + b;
   return result;
}

int main(int argc, char* argv[])
{
   sum(1, 4);
   return 0;
}




* 调用栈与机器架构有          , 这里以x86为例.
简单类型函数调用
                                   ...
int sum(int a, int b) {
   int result = a + b;              4
   return result;
}
                                    1
int main(int argc, char* argv[])
{
   sum(1, 4);
   return 0;
}




* 调用栈与机器架构有          , 这里以x86为例.
简单类型函数调用
                                        ...
int sum(int a, int b) {
   int result = a + b;                   4
   return result;
}
                                         1
int main(int argc, char* argv[])
{                                  Return Address
   sum(1, 4);
   return 0;
}




* 调用栈与机器架构有          , 这里以x86为例.
简单类型函数调用
                                              ...
int sum(int a, int b) {             5
   int result = a + b;             eax         4
   return result;
}
                                               1
int main(int argc, char* argv[])
{                                        Return Address
   sum(1, 4);
   return 0;
}                                  ebp     Saved ebp


                                   esp        sum


* 调用栈与机器架构有          , 这里以x86为例.
类类型参数传递
class Money {
 public:
   Money Add(Money money);

  private:
   uint64_t amount;
};

Money item(700);
Money freight(10);

Money total = item.Add(freight);
类类型参数传递
                                         ...
class Money {
 public:
   Money Add(Money money);         temp - Money(10)

  private:
   uint64_t amount;
};

Money item(700);
Money freight(10);

Money total = item.Add(freight);
类类型参数传递
                                         ...
class Money {
 public:
   Money Add(Money money);         temp - Money(10)

  private:
   uint64_t amount;
};                                 Return Address

Money item(700);
Money freight(10);

Money total = item.Add(freight);
类类型参数传递
                                               ...
class Money {
 public:
   Money Add(Money money);               temp - Money(10)

  private:
   uint64_t amount;
};                                       Return Address

Money item(700);
Money freight(10);                 ebp      Saved ebp

Money total = item.Add(freight);   esp         sum
类类型返回值
class Money {
 public:
   Money Add(Money money);

  private:
   uint64_t amount;
};

Money item(700);
Money freight(10);

Money total = item.Add(freight);
类类型返回值
class Money {                      void Money_Add(
 public:                               Money* this,
   Money Add(Money money);             Money* ret,
                                       Money money)
  private:                         {
   uint64_t amount;                    Money result = ...;
};                                     *ret = result;
                                   }
Money item(700);                   ...
Money freight(10);
                                   Money temp;
Money total = item.Add(freight);   Money_Add(&item, &temp, freight);
                                   Money total = temp;
                                   temp.Money::~Money();
类类型返回值
class Money {                      void Money_Add(
 public:                               Money* this,
   Money Add(Money money);             Money* ret,
                                       Money money)
  private:                         {
   uint64_t amount;                    Money result = ...;
};                                     *ret = result;
                                   }
Money item(700);                   ...
Money freight(10);
                                   Money temp;
Money total = item.Add(freight);   Money_Add(&item, &temp, freight);
                                   Money total = temp;
                                   temp.Money::~Money();
临时对象
• 函数调用的参数传递与返回

• 额外的对象构造与析构

• 额外的对象拷贝

• 可能戏剧性的影响程序效率
Tips 2


   Prefer pass-by-reference
      to pass-by-value
Return Value Optimization
void Money_Add(
  Money* this,
  Money* ret,
  Money money)
{
  Money result = ...;
  *ret = result;
}

Money item(700);
Money freight(10);

Money temp;
Money_Add(&item, &temp, freight);
Money total = temp;
Return Value Optimization
void Money_Add(                     void Money_Add(
  Money* this,                        Money* this,
  Money* ret,                         Money* ret,
  Money money)                        Money money)
{                                   {
  Money result = ...;                 *ret = ...;
  *ret = result;                    }
}
                                    Money item(700);
Money item(700);                    Money freight(10);
Money freight(10);
                                    Money temp;
Money temp;                         Money total;
Money_Add(&item, &temp, freight);   Money_Add(&item, &total, freight);
Money total = temp;
Return Value Optimization
void Money_Add(                     void Money_Add(
  Money* this,                        Money* this,
  Money* ret,                         Money* ret,
  Money money)                        Money money)
{                                   {
  Money result = ...;                 *ret = ...;
  *ret = result;                    }
}
                                    Money item(700);
Money item(700);                    Money freight(10);
Money freight(10);
                                    Money temp;
Money temp;                         Money total;
Money_Add(&item, &temp, freight);   Money_Add(&item, &total, freight);
Money total = temp;
std::string

• Implementations

  - Eager Copy

  - CoW - Copy on Write

  - SSO - Small String Optimization
Copy on Write
         string
   data : char*
Copy on Write

    string            "hello"
data : char*


                     5 30 1 h e   l   l   o ...
Copy on Write

    string              "hello"
data : char*
                        capacity


                      5 30 1 h e      l    l   o ...
                     size     引用计数   数据区
SSO
      string
data : char*
size : size_t
capacity : size_t
buffer : char[16]
Small String
      string                "hello"
data : char*
                          0x12345678
size : size_t
capacity : size_t
buffer : char[16]
                               5

                        h e l l o
Big String
"hell ..."        h e   l   l ...

0x12345678


   20



   32
Tips 3


  Critically Analyze What
   You Read And Hear
静态变量初始化

Animal animal("Lion");

int Foo() {
   ...
}

int num = Foo();
静态变量初始化

Animal animal("Lion");   void __sti_ii() {
                           animal.Animal::Animal();
int Foo() {                num = Foo();
   ...                   }
}
                         void __std_ii() {
int num = Foo();           animal.Animal::~Animal();
                         }
inline vs. iterator
vector<int>::iterator it = vec.begin();
vector<int>::iterator end = vec.end();    for (vector<int>::iterator it = vec.begin();
for (; it != end; ++it) {                      it != vec.end(); ++it) {


}                                         }
inline vs. iterator
vector<int>::iterator it = vec.begin();
vector<int>::iterator end = vec.end();    for (vector<int>::iterator it = vec.begin();
for (; it != end; ++it) {                      it != vec.end(); ++it) {

     it = vec.erase(it);                        it = vec.erase(it);
}                                         }
inline vs. iterator
vector<int>::iterator it = vec.begin();
vector<int>::iterator end = vec.end();    for (vector<int>::iterator it = vec.begin();
for (; it != end; ++it) {                      it != vec.end(); ++it) {

     it = vec.erase(it);                        it = vec.erase(it);
}                                         }
Tips 4


         Don't Assume It,
            Prove It
Prove I t!
• Only Code Never Lies

• Assembly Language

• g++

  - -S

• nm
References
• Bjarne Stroustrup. 1994. The Design And
  Evolution of C++

• Stanley B. Lippman. 1996. Inside the C++
  Object Model

• Scott Meyers. 2006. Effective C++

• 陈硕. 2012. C++工程实践
Q&A
Thanks for your time

More Related Content

What's hot

Lifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeLifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During Lunchtime
Alexander Shopov
 
Lifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeLifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java Bytecode
Alexander Shopov
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futures
nithinmohantk
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
Duoyi Wu
 
I Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeI Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java Bytecode
Alexander Shopov
 
Detecting Occurrences of Refactoring with Heuristic Search
Detecting Occurrences of Refactoring with Heuristic SearchDetecting Occurrences of Refactoring with Heuristic Search
Detecting Occurrences of Refactoring with Heuristic Search
Shinpei Hayashi
 
How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
Anna (gaar4ica) Shcherbinina
 
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
Coen De Roover
 
Pizza compiler
Pizza compilerPizza compiler
Pizza compiler
Sander Mak (@Sander_Mak)
 
Actor Model and C++: what, why and how?
Actor Model and C++: what, why and how?Actor Model and C++: what, why and how?
Actor Model and C++: what, why and how?
Yauheni Akhotnikau
 
A Recommender System for Refining Ekeko/X Transformation
A Recommender System for Refining Ekeko/X TransformationA Recommender System for Refining Ekeko/X Transformation
A Recommender System for Refining Ekeko/X Transformation
Coen De Roover
 
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Shinpei Hayashi
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
Andrey Upadyshev
 
Learn Ruby by Reading the Source
Learn Ruby by Reading the SourceLearn Ruby by Reading the Source
Learn Ruby by Reading the Source
Burke Libbey
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
chenge2k
 
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume LaforgeGR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf
 
Latest C++ Interview Questions and Answers
Latest C++ Interview Questions and AnswersLatest C++ Interview Questions and Answers
Latest C++ Interview Questions and Answers
DaisyWatson5
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Group
baroquebobcat
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
Ganesh Samarthyam
 

What's hot (20)

Lifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeLifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During Lunchtime
 
Lifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeLifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java Bytecode
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futures
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
I Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeI Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java Bytecode
 
Detecting Occurrences of Refactoring with Heuristic Search
Detecting Occurrences of Refactoring with Heuristic SearchDetecting Occurrences of Refactoring with Heuristic Search
Detecting Occurrences of Refactoring with Heuristic Search
 
How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
 
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
A Logic Meta-Programming Foundation for Example-Driven Pattern Detection in O...
 
Pizza compiler
Pizza compilerPizza compiler
Pizza compiler
 
Actor Model and C++: what, why and how?
Actor Model and C++: what, why and how?Actor Model and C++: what, why and how?
Actor Model and C++: what, why and how?
 
A Recommender System for Refining Ekeko/X Transformation
A Recommender System for Refining Ekeko/X TransformationA Recommender System for Refining Ekeko/X Transformation
A Recommender System for Refining Ekeko/X Transformation
 
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
 
Learn Ruby by Reading the Source
Learn Ruby by Reading the SourceLearn Ruby by Reading the Source
Learn Ruby by Reading the Source
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
 
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume LaforgeGR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
 
Latest C++ Interview Questions and Answers
Latest C++ Interview Questions and AnswersLatest C++ Interview Questions and Answers
Latest C++ Interview Questions and Answers
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Group
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 

Similar to Mysterious c++

UNIT IV (1).ppt
UNIT IV (1).pptUNIT IV (1).ppt
UNIT IV (1).ppt
VGaneshKarthikeyan
 
Unit iv
Unit ivUnit iv
Unit iv
snehaarao19
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
Sven Efftinge
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
Heiko Behrens
 
Intro to Java for C++ Developers
Intro to Java for C++ DevelopersIntro to Java for C++ Developers
Intro to Java for C++ Developers
Zachary Blair
 
Introduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IOIntroduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IO
Liran Zvibel
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
Brian Hsu
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
Mohammad Shaker
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
application developer
 
Perl-C/C++ Integration with Swig
Perl-C/C++ Integration with SwigPerl-C/C++ Integration with Swig
Perl-C/C++ Integration with Swig
David Beazley (Dabeaz LLC)
 
Swift core
Swift coreSwift core
Swift core
Yusuke Kita
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
 
Lua. The Splendors and Miseries of Game Scripting
Lua. The Splendors and Miseries of Game ScriptingLua. The Splendors and Miseries of Game Scripting
Lua. The Splendors and Miseries of Game Scripting
DevGAMM Conference
 
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
lennartkats
 
Virtual Separation of Concerns
Virtual Separation of ConcernsVirtual Separation of Concerns
Virtual Separation of Concerns
chk49
 
tutorial5
tutorial5tutorial5
tutorial5
tutorialsruby
 
tutorial5
tutorial5tutorial5
tutorial5
tutorialsruby
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Anna Brzezińska
 
Towards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages ToolchainTowards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages Toolchain
Attila Szegedi
 

Similar to Mysterious c++ (20)

UNIT IV (1).ppt
UNIT IV (1).pptUNIT IV (1).ppt
UNIT IV (1).ppt
 
Unit iv
Unit ivUnit iv
Unit iv
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Intro to Java for C++ Developers
Intro to Java for C++ DevelopersIntro to Java for C++ Developers
Intro to Java for C++ Developers
 
Introduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IOIntroduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IO
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Memory Management with Java and C++
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 
Perl-C/C++ Integration with Swig
Perl-C/C++ Integration with SwigPerl-C/C++ Integration with Swig
Perl-C/C++ Integration with Swig
 
Swift core
Swift coreSwift core
Swift core
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
Lua. The Splendors and Miseries of Game Scripting
Lua. The Splendors and Miseries of Game ScriptingLua. The Splendors and Miseries of Game Scripting
Lua. The Splendors and Miseries of Game Scripting
 
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
Mixing Source and Bytecode: A Case for Compilation By Normalization (OOPSLA 2...
 
Virtual Separation of Concerns
Virtual Separation of ConcernsVirtual Separation of Concerns
Virtual Separation of Concerns
 
tutorial5
tutorial5tutorial5
tutorial5
 
tutorial5
tutorial5tutorial5
tutorial5
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 
Towards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages ToolchainTowards JVM Dynamic Languages Toolchain
Towards JVM Dynamic Languages Toolchain
 

Recently uploaded

Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
Techgropse Pvt.Ltd.
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 

Recently uploaded (20)

Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 

Mysterious c++

  • 1. Mysterious c++ Traps, Pitfalls and Secrets Kent Wang Jun 1, 2012
  • 2. Why this talk • 警惕靠巧合编程 • 勿在浮沙筑高台 • 了若指掌方可收放自如 • 见山非山, 见水非水
  • 3.
  • 12. sizeof class A { class B { class C { }; char c; virtual void foo(); }; char c; };
  • 13. sizeof class A { class B { class C { }; char c; virtual void foo(); }; char c; }; 1
  • 14. sizeof class A { class B { class C { }; char c; virtual void foo(); }; char c; }; 1 4
  • 15. sizeof class A { class B { class C { }; char c; virtual void foo(); }; char c; }; 1 4 8
  • 16. Constructor class Animal { public: Animal() { Animal("Lion", 21); Run(); } Animal(const string& name, int age); virtual void Run() = 0; };
  • 17. Constructor class Animal { public: Animal() { Animal("Lion", 21); Run(); } Animal(const string& name, int age); virtual void Run() = 0; };
  • 18.
  • 24. Function Object Member Function pointer Temporal Object dynamic_cast Function pointer Pass By Reference Pure Virtual Class RTTI typeid Overloading Pass By Value Pure Virtual Function Copy Constructor Virtual Function Multiple Inheritance Constructor Dynamic Binding Inheritance Exception Destructor Class Virtual Inheritance Friend Template String Adaptor Namespace STL Operator New RAII Iterator Function Template Class Template Template Specialization Memory Management Partial Specialization Smart Pointer Reference Preprocessor Template Meta Programming
  • 25. 知乎? • 构造和析构函数机制是如何实现的? • 函数调用是如何传递及返回对象的? • 函数重载是如何实现的? • 多态是如何实现的? • 常机制是如何实现的?为何我们不用? • 静态变量是如何初始化的?
  • 26. Tips 1 Don't live with unknown unknowns
  • 27. What to talk • C++语言演化历史 • Object Memory Layout • 函数调用语义及临时对象 • 静态变量初始化
  • 28. What NOT to talk • 语法细节 • 二进制兼容性 • Exception Handling • Template & Generic Programming • C++11 (C++0x)
  • 29. Outline • 青梅煮酒论英雄 • 天机亦可泄露 - 对象内存模型 - 函数转换 - 函数调用 - 临时对象
  • 31. Timeline 2011 1980 1989 C++11 C with class CFront 2.0 1992 HP C++ Lambda Expression Class Multiple Inheritance Automatic Type Inheritance Abstract Class Exception Threading 1983 - 1986 1991 1996 C++ - CFront 1.1 CFront 3.0 C++ 98/03 Virtual Function Template STL Overloading Namespace Reference
  • 34. 缘起 值语义 零负担 C兼容性 惯用法 编译器隐 藏操作
  • 35. C兼容性 • class Foo{}; - unnamed structure in C • Header File • Preprocessor / macros
  • 36. C兼容性 • class Foo{}; - unnamed structure in C struct { int a; int b • Header File } foo; foo.a = 10; • Preprocessor / macros
  • 37. 零负担 • 不对栈变量自动初始化 • Object on Stack • 默认构造函数不对POD类型进行初始化 • 成员函数默认为非虚函数
  • 39. 值语义 Person kent("kent"); Person lazy = kent; kent "kent" lazy "kent"
  • 42. Not very good at OO • No reflection and dynamic creation • Object lifetime management • Complex syntax stops refactoring tools
  • 43.
  • 45.
  • 47. C++ is deterministic • Destructing is determinate - No GC • Performance is predictable - C++ is fast only when coders are experts - Java is almost as fast, much higher productivity
  • 48. Where the Focus Is Efficiency Flexibility Abstraction Productivity C non-goal non-goal C++ non-goal at the at the Java, C# expense of expense of
  • 49. Conclusion • There are only two kinds of languages - The ones people always complain about - The ones nobody uses • C++ is an undoubted success • One language doesn’t fit all - Important to known when and when not
  • 52. 简单对象 class Animal { public: void Run(); private: char* name; int age; char sex; };
  • 53. 简单对象 class Animal { name public: void Run(); private: age char* name; int age; char sex; }; Sex Alignment
  • 54. 单一继承 class Animal { public: void Run(); private: char* name; int age; char sex; }; class Lion : public Animal { private: char* address; };
  • 55. 单一继承 class Animal { address public: void Run(); private: name char* name; int age; char sex; }; age class Lion : public Animal { private: char* address; Sex Alignment };
  • 56. 虚函数 class Animal { public: void Run(); virtual void Say(); private: char* name; int age; char sex; }; * vptr的偏移量与编译器实现有 .
  • 57. 虚函数 class Animal { vptr public: void Run(); virtual void Say(); name private: char* name; age int age; char sex; }; Sex Alignment * vptr的偏移量与编译器实现有 .
  • 58. vptr and vtbl vptr name age Sex Alignment
  • 59. vptr and vtbl vptr 0 type_info type_info name 1 Say &Animal::Say age Sex Alignment vtbl$Animal
  • 60. 带虚函数的继承 class Animal { public: virtual void Run(); virtual void Say(); private: char* name; int age; char sex; }; class Lion { public: virtual void Say(); };
  • 61. 带虚函数的继承 class Animal { public: virtual void Run(); virtual void Say(); vptr private: name char* name; int age; char sex; age }; class Lion { Sex Alignment public: virtual void Say(); };
  • 62. vptr and vtbl vptr name age Sex Alignment
  • 63. vptr and vtbl vptr 0 type_info type_info name 1 Run &Animal::Run age 2 Say &Lion::Say Sex Alignment vtbl$Lion
  • 64. M o re • 多重继承 • 带虚函数的多重继承 • 虚继承 • 带虚函数的虚继承 • 多重虚继承
  • 65. 函数转换 class Animal { public: void Run(); private: ... }; Animal a; a.Run(); * 真实情况下编译器会对函数名称进行编码,即name mangling.
  • 66. 函数转换 class Animal { public: void Run(); private: ... }; Animal a; a.Run(); * 真实情况下编译器会对函数名称进行编码,即name mangling.
  • 67. 函数转换 class Animal { void Animal_Run(Animal* this) public: { void Run(); ... } private: ... Animal a; }; Animal_Run(&a); Animal a; a.Run(); * 真实情况下编译器会对函数名称进行编码,即name mangling.
  • 68. 函数转换 class Animal { void Animal_Run(Animal* this) public: { void Run(); ... } private: ... Animal a; }; Animal_Run(&a); Animal a; a.Run(); * 真实情况下编译器会对函数名称进行编码,即name mangling.
  • 69. 虚函数转换 class Animal { public: void Run(); virtual void Say(); private: ... }; Animal a; a.Say(); Animal* p = &a; p->Say();
  • 70. 虚函数转换 class Animal { void Animal_ctor(Animal* this) public: { void Run(); this.vptr = &Animal_vtbl; virtual void Say(); } private: void Animal_Say(Animal* this) ... { }; } Animal a; Animal a; a.Say(); Animal_ctor(&a); Animal_Say(&a); Animal* p = &a; Animal* p = &a; p->Say(); (*(p->vptr[1]))(p);
  • 71. 虚函数转换 class Animal { void Animal_ctor(Animal* this) public: { void Run(); this.vptr = &Animal_vtbl; virtual void Say(); } private: void Animal_Say(Animal* this) ... { }; } Animal a; Animal a; a.Say(); Animal_ctor(&a); Animal_Say(&a); Animal* p = &a; Animal* p = &a; p->Say(); (*(p->vptr[1]))(p);
  • 73. 简单类型函数调用 int sum(int a, int b) { int result = a + b; return result; } int main(int argc, char* argv[]) { sum(1, 4); return 0; } * 调用栈与机器架构有 , 这里以x86为例.
  • 74. 简单类型函数调用 ... int sum(int a, int b) { int result = a + b; 4 return result; } 1 int main(int argc, char* argv[]) { sum(1, 4); return 0; } * 调用栈与机器架构有 , 这里以x86为例.
  • 75. 简单类型函数调用 ... int sum(int a, int b) { int result = a + b; 4 return result; } 1 int main(int argc, char* argv[]) { Return Address sum(1, 4); return 0; } * 调用栈与机器架构有 , 这里以x86为例.
  • 76. 简单类型函数调用 ... int sum(int a, int b) { 5 int result = a + b; eax 4 return result; } 1 int main(int argc, char* argv[]) { Return Address sum(1, 4); return 0; } ebp Saved ebp esp sum * 调用栈与机器架构有 , 这里以x86为例.
  • 77. 类类型参数传递 class Money { public: Money Add(Money money); private: uint64_t amount; }; Money item(700); Money freight(10); Money total = item.Add(freight);
  • 78. 类类型参数传递 ... class Money { public: Money Add(Money money); temp - Money(10) private: uint64_t amount; }; Money item(700); Money freight(10); Money total = item.Add(freight);
  • 79. 类类型参数传递 ... class Money { public: Money Add(Money money); temp - Money(10) private: uint64_t amount; }; Return Address Money item(700); Money freight(10); Money total = item.Add(freight);
  • 80. 类类型参数传递 ... class Money { public: Money Add(Money money); temp - Money(10) private: uint64_t amount; }; Return Address Money item(700); Money freight(10); ebp Saved ebp Money total = item.Add(freight); esp sum
  • 81. 类类型返回值 class Money { public: Money Add(Money money); private: uint64_t amount; }; Money item(700); Money freight(10); Money total = item.Add(freight);
  • 82. 类类型返回值 class Money { void Money_Add( public: Money* this, Money Add(Money money); Money* ret, Money money) private: { uint64_t amount; Money result = ...; }; *ret = result; } Money item(700); ... Money freight(10); Money temp; Money total = item.Add(freight); Money_Add(&item, &temp, freight); Money total = temp; temp.Money::~Money();
  • 83. 类类型返回值 class Money { void Money_Add( public: Money* this, Money Add(Money money); Money* ret, Money money) private: { uint64_t amount; Money result = ...; }; *ret = result; } Money item(700); ... Money freight(10); Money temp; Money total = item.Add(freight); Money_Add(&item, &temp, freight); Money total = temp; temp.Money::~Money();
  • 84. 临时对象 • 函数调用的参数传递与返回 • 额外的对象构造与析构 • 额外的对象拷贝 • 可能戏剧性的影响程序效率
  • 85. Tips 2 Prefer pass-by-reference to pass-by-value
  • 86. Return Value Optimization void Money_Add( Money* this, Money* ret, Money money) { Money result = ...; *ret = result; } Money item(700); Money freight(10); Money temp; Money_Add(&item, &temp, freight); Money total = temp;
  • 87. Return Value Optimization void Money_Add( void Money_Add( Money* this, Money* this, Money* ret, Money* ret, Money money) Money money) { { Money result = ...; *ret = ...; *ret = result; } } Money item(700); Money item(700); Money freight(10); Money freight(10); Money temp; Money temp; Money total; Money_Add(&item, &temp, freight); Money_Add(&item, &total, freight); Money total = temp;
  • 88. Return Value Optimization void Money_Add( void Money_Add( Money* this, Money* this, Money* ret, Money* ret, Money money) Money money) { { Money result = ...; *ret = ...; *ret = result; } } Money item(700); Money item(700); Money freight(10); Money freight(10); Money temp; Money temp; Money total; Money_Add(&item, &temp, freight); Money_Add(&item, &total, freight); Money total = temp;
  • 89. std::string • Implementations - Eager Copy - CoW - Copy on Write - SSO - Small String Optimization
  • 90. Copy on Write string data : char*
  • 91. Copy on Write string "hello" data : char* 5 30 1 h e l l o ...
  • 92. Copy on Write string "hello" data : char* capacity 5 30 1 h e l l o ... size 引用计数 数据区
  • 93. SSO string data : char* size : size_t capacity : size_t buffer : char[16]
  • 94. Small String string "hello" data : char* 0x12345678 size : size_t capacity : size_t buffer : char[16] 5 h e l l o
  • 95. Big String "hell ..." h e l l ... 0x12345678 20 32
  • 96. Tips 3 Critically Analyze What You Read And Hear
  • 98. 静态变量初始化 Animal animal("Lion"); void __sti_ii() { animal.Animal::Animal(); int Foo() { num = Foo(); ... } } void __std_ii() { int num = Foo(); animal.Animal::~Animal(); }
  • 99. inline vs. iterator vector<int>::iterator it = vec.begin(); vector<int>::iterator end = vec.end(); for (vector<int>::iterator it = vec.begin(); for (; it != end; ++it) { it != vec.end(); ++it) { } }
  • 100. inline vs. iterator vector<int>::iterator it = vec.begin(); vector<int>::iterator end = vec.end(); for (vector<int>::iterator it = vec.begin(); for (; it != end; ++it) { it != vec.end(); ++it) { it = vec.erase(it); it = vec.erase(it); } }
  • 101. inline vs. iterator vector<int>::iterator it = vec.begin(); vector<int>::iterator end = vec.end(); for (vector<int>::iterator it = vec.begin(); for (; it != end; ++it) { it != vec.end(); ++it) { it = vec.erase(it); it = vec.erase(it); } }
  • 102. Tips 4 Don't Assume It, Prove It
  • 103. Prove I t! • Only Code Never Lies • Assembly Language • g++ - -S • nm
  • 104. References • Bjarne Stroustrup. 1994. The Design And Evolution of C++ • Stanley B. Lippman. 1996. Inside the C++ Object Model • Scott Meyers. 2006. Effective C++ • 陈硕. 2012. C++工程实践
  • 105. Q&A

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n
  114. \n
  115. \n
  116. \n
  117. \n
  118. \n
  119. \n
  120. \n
  121. \n
  122. \n
  123. \n
  124. \n
  125. \n
  126. \n
  127. \n
  128. \n
  129. \n
  130. \n
  131. \n
  132. \n
  133. \n