Construct object with itself as reference?

后端 未结 6 1590
小鲜肉
小鲜肉 2021-02-02 03:26

I just realised that this program compiles and runs (gcc version 4.4.5 / Ubuntu):

#include 
using namespace std;

class Test
{
public:
  // copyc         


        
6条回答
  •  北海茫月
    2021-02-02 04:08

    I have no idea how this relates to the specification, but this is how I see it:

    When you do Test a(a); it allocates space for a on the stack. Therefore the location of a in memory is known to the compiler at the start of main. When the constructor is called (the memory is of course allocated before that), the correct this pointer is passed to it because it's known.

    When you do Test *b = new Test(*b);, you need to think of it as two steps. First the object is allocated and constructed, and then the pointer to it is assigned to b. The reason you get the message you get is that you're essentially passing in an uninitialized pointer to the constructor, and the comparing it with the actual this pointer of the object (which will eventually get assigned to b, but not before the constructor exits).

提交回复
热议问题