Construct object with itself as reference?

后端 未结 6 1596
小鲜肉
小鲜肉 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:22

    The second one where you use new is actually easier to understand; what you're invoking there is exactly the same as:

    Test *b;
    b = new Test(*b);
    

    and you're actually performing an invalid dereference. Try to add a << &other << to your cout lines in the constructor, and make that

    Test *b = (Test *)0xFOOD1E44BADD1E5;
    

    to see that you're passing through whatever value a pointer on the stack has been given. If not explicitly initialized, that's undefined. But even if you don't initialize it with some sort of (in)sane default, it'll be different from the return value of new, as you found out.

    For the first, think of it as an in-place new. Test a is a local variable not a pointer, it lives on the stack and therefore its memory location is always well defined - this is very much unlike a pointer, Test *b which, unless explicitly initialized to some valid location, will be dangling.

    If you write your first instantiation like:

    Test a(*(&a));
    

    it becomes clearer what you're invoking there.

    I don't know a way to make the compiler disallow (or even warn) about this sort of self-initialization-from-nowhere through the copy constructor.

提交回复
热议问题