Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self reference in construction

Tags:

c++

I have just discovered that the following code compiles with both gcc 5.4 and the Intel compiler 18.0.2. Clang 6.0.0 just gives a warning.

#include <vector>

int main() {
  std::vector<double> v = v;

  return 0;
}

I had a bug in my code that was very similar and I am scared that those kind of code can compile. My question are:

  • Is it legal C++? If yes, what is it supposed to do?
  • How to catch those "bugs" at compile time?
like image 221
InsideLoop Avatar asked May 04 '18 07:05

InsideLoop


People also ask

What is an example of self-reference?

In the context of language, self-reference is used to denote a statement that refers to itself or its own referent. The most famous example of a self-referential sentence is the liar sentence: “This sentence is not true.” Self-reference is often used in a broader context as well.

What does self-reference means?

Definition of self-reference : the act or an instance of referring or alluding to oneself or itself … their discourse can become dominated by words expressing confidence, like … self-reference that can favour the "royal we" over "I."—

How does self referencing work?

Self-reference occurs in literature and film when an author refers to his or her own work in the context of the work itself.

What is a self-referential system?

A self-referential system is one where the parts cannot distinguish the model of the whole from themselves even though the parts are individually not the same as the whole (collectively). The peculiar nature of life and thus biological systems is that they are able to construct themself from the inside out.


Video Answer


1 Answers

Is it legal C++? If yes, what is it supposed to do?

It's a well-formed program, but it exhibits Undefined Behaviour, because it reads an uninitialised variable. This means there are no constraints on its behaviour (it can legally do literally anything).

How to catch those "bugs" at compile time?

Enable enough warnings and build with "treat warnings as errors." With enough warnings on, gcc 5.4 catches it correctly. Note that in the case of gcc, this also requires turning optimisation on, because gcc does some analyses (such as unused variables) only when optimising.

like image 196
Angew is no longer proud of SO Avatar answered Oct 19 '22 05:10

Angew is no longer proud of SO