Optimization due to constructor initializer list

后端 未结 8 1793
故里飘歌
故里飘歌 2020-12-13 21:23

Constructors should initialize all its member objects through initializer list if possible. It is more efficient than building the constructors via assign

8条回答
  •  猫巷女王i
    2020-12-13 22:06

    Suppose you have a data member in your class which is std::string type. When the constructor of this class is executed, the default constructor string class would be called automatically because objects are initialized before the body of the constructor.

    If you are assigning the string inside the body of the constructor, then a temporary object would be created and given to the string's assignment operator. The temporary object will be destroyed at the end of the assignment statement. If you do this in the initializer list, a temporary object will not be created.

    class Person
    {
    public:
        Person(string s);
        ~Person();
    private:
        string name;
    };
    
    
    // case 1
    Person::Person(string s)
    {
       name = s;   // creates a temporary object
    }
    
    // case 2
    Person::Person(string s):name(s) {} // whereas this will not create a temporary object.
    

提交回复
热议问题