2

Here is what my code looks like which is very simple:

#include <stdio.h>

class Test
{
public:
   Test()
   {
      printf ("contructor !\n");
   }

   ~Test()
   {
      printf ("destructor !\n");
   }

   Test(const Test& test)
   {
      printf ("copy contructor !\n");
   }
};


int main()
{
    Test xyz(xyz);
    return 0;
}

Then I type g++ a.cpp; ./a.out

It output: copy contructor ! destructor !

but no contructor output !
I`m confused, is it a bug of compiler ?

see pic

li xin
  • 29
  • 1
  • 4
    Possible duplicate of [What's the behavior of an uninitialized variable used as its own initializer?](https://stackoverflow.com/questions/54200465/whats-the-behavior-of-an-uninitialized-variable-used-as-its-own-initializer) – tigertang Nov 26 '19 at 05:41
  • 1
    Why do you expect a default constructor to be called? There's only one instance of `Test` in the code, and it's constructed using the copy constructor, not the default one. – HolyBlackCat Nov 26 '19 at 05:54
  • 4
    No, it's not a compiler bug. Always blame your own program before the tooling. – StoryTeller - Unslander Monica Nov 26 '19 at 06:23

1 Answers1

2

In the line where you create the object xyz the address of this object in known even before the object is created. That means that you may take the reference to this (not created yet) object and pass it as a parameter to the constructor of this object itself. From the compiler point of view it is possible. You don't initialize any fields, so you don't observe any fields initialized with junk. Anyway, you get what you deserve.

Is that just a theoretical question or you really have a practical purpose?

Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40