Member Variable Initialization with Same-Named Constructor Arguments
In C , it is possible to initialize member variables using constructor arguments with the same names as the member variables. This technique, as demonstrated in the example below, has been confirmed to work without warnings or errors when compiled with g 4.4 and clang .
class Blah { std::vector<int> vec; public: Blah(std::vector<int> vec): vec(vec) {} void printVec() { for (unsigned int i = 0; i < vec.size(); i++) printf("%i ", vec.at(i)); printf("\n"); } };
According to the C standard (§12.6.2/7), this initialization is legal and guaranteed to work. The names in the expression-list of a mem-initializer are evaluated in the scope of the constructor, allowing the this pointer to be used to refer to the object being initialized.
In the example above, the constructor argument vec is initialized to the member variable vec with the same name. This initialization occurs each time an object of class Blah is created.
Recommendation
Consider accepting the constructor parameter as a const reference to avoid unnecessary copying of the original vector object, as seen below:
Blah(const std::vector<int> & vec): vec(vec) {}
The above is the detailed content of Can C Member Variables Be Initialized Using Constructor Arguments with the Same Name?. For more information, please follow other related articles on the PHP Chinese website!