C. 49: Prefer the Initialization to the Assignment in Constructors
c. 49: constructor should do instead is to initialize assignment
Reason (reason)
An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
Initialization clearly indicates that the initialization is done rather than assignment, but can be made more beautiful and more efficient. Prevent incorrect "use before the assignment," the.
Example, good (good examples)
class A { // Good
string s1;
public:
A(czstring p) : s1{p} { } // GOOD: directly construct (and the C-string is explicitly named)
// ...
};
Example, bad (negative sample)
class B { // BAD
string s1;
public:
B(const char* p) { s1 = p; } // BAD: default constructor followed by assignment
// ...
};
class C { // UGLY, aka very bad
int* p;
public:
C() { cout << *p; p = new int{10}; } // accidental use before initialized
// ...
};
Example, better still (better example)
Instead of those const char*s we could use gsl::string_span or (in C++17) std::string_view as a more general way to present arguments to a function:
Relative to those const char * s, we should be able to use gsl :: string_span or (C ++ 17 introduced) std :: string_view as expressed as a function of the more popular way to anger parameters (https://github.com/isocpp/ CppCoreGuidelines / blob / master / CppCoreGuidelines.md # Rstr-view).
class D { // Good
string s1;
public:
A(string_view v) : s1{v} { } // GOOD: directly construct
// ...
};
Description link
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c49-prefer-initialization-to-assignment-in-constructors
I think this article helpful? Welcome thumbs up and share it with more people.
Read more updated articles, please pay attention to micro-channel public number of object-oriented thinking []