Why can const class & be initialized for itself?

It struck me very stupidly, but it's hard to spot a mistake today. Here is the relevant code:

class Vector; class PointIterator { const Vector & x; const Vector & yv; PointIterator(const Vector & xv, const Vector & yvo) : x(xv), yv(yv) { ;}; // ^^ here is wrong }; 

Why is such code legal C ++? Is there a situation where you can use the yv variable? I know similar questions about int x = x+1; , (see this question ), but until the last one is correctly initialized, you can still use the variable x , while in the code above, I don't think you can use yv .

Bonus Point: Is there any compilation option that would make me discover this? (preferably using gcc, but I also use clang), in addition to warning the β€œunused argument” (I have a lot of them, I know I have to clear them).

+4
source share
1 answer

If you compile g++ -O0 -g main.cpp -Wall -pedantic -Wextra -std=c++14 -o go

 main.cpp: In constructor 'PointIterator::PointIterator(const Vector&, const Vector&)': main.cpp:11:5: warning: 'PointIterator::yv' is initialized with itself [-Winit-self] PointIterator(const Vector & xv, const Vector & yvo) : ^~~~~~~~~~~~~ main.cpp:11:53: warning: unused parameter 'yvo' [-Wunused-parameter] PointIterator(const Vector & xv, const Vector & yvo) : 

As you can see, you get a warning twice. One for self init and one for unused parameter. Excellent!

Same thing for clang: clang++ -O0 -g main.cpp -Wall -pedantic -Wextra -std=c++14 -o go

 main.cpp:12:19: warning: reference 'yv' is not yet bound to a value when used here [-Wuninitialized] x(xv), yv(yv) { ;}; ^ main.cpp:11:53: warning: unused parameter 'yvo' [-Wunused-parameter] PointIterator(const Vector & xv, const Vector & yvo) : ^ main.cpp:8:20: warning: private field 'x' is not used [-Wunused-private-field] const Vector & x; 

Thus, clang also reports a problem that uninitialized ref is used before init. Excellent!

What you will learn: * Use multiple compilers with the highest warning level to get all warnings!

This is what we do for all of our code, especially in unit tests related to code coverage.

And you should use a coding guide that makes it easy to identify such problems through a review. Perhaps use "m_" for the vars classes or "_var" for the options or whatever you prefer. Var names with just a list of letters instead of name names are not so good.

+5
source

Source: https://habr.com/ru/post/1268414/


All Articles