114

I am surprised to accidentally discover that the following works:

#include <iostream>            
int main(int argc, char** argv)
{
  struct Foo {
    Foo(Foo& bar) {
      std::cout << &bar << std::endl;
    }
  };
  Foo foo(foo); // I can't believe this works...
  std::cout << &foo << std::endl; // but it does...
}

I am passing the address of the constructed object into its own constructor. This looks like a circular definition at the source level. Do the standards really allow you to pass an object into a function before the object is even constructed or is this undefined behavior?

I suppose it's not that odd given that all class member functions already have a pointer to the data for their class instance as an implicit parameter. And the layout of the data members is fixed at compile time.

Note, I'm NOT asking if this is useful or a good idea; I'm just tinkering around to learn more about classes.

17
  • 1
    @ShafikYaghmour Why did you delete your answer? Just add a quotation of [basic.life]p6 for restrictions.
    – dyp
    Commented Sep 16, 2015 at 12:35
  • 2
    Yes, that's fine; it's essentially the same as using this in a constructor, with all its pitfalls.
    – Kerrek SB
    Commented Sep 16, 2015 at 12:38
  • 2
    Isn't this more like size_t x = sizeof(x) ? The constructor of an object is called at a point where the memory is allocated (from an unspecified source). As long as you only depend on properties of the storage, and not on any value interpretation, things should be safe.
    – MSalters
    Commented Sep 16, 2015 at 12:41
  • 1
    @MSalters There's a subtle question as to whether or not the storage is allocated prior to binding the object to the reference, which is before the constructor call.
    – dyp
    Commented Sep 16, 2015 at 12:45
  • 1
    Shafik, at your suggestion, I temporarily unaccepted your answer, though it was already plenty deep for me :) Commented Sep 16, 2015 at 13:00

3 Answers 3

68

This is not undefined behavior. Although foo is uninitialized, you are using it a way that is allowed by the standard. After space is allocated for an object but before it is fully initialized, you are allowed to use it limited ways. Both binding a reference to that variable and taking its address are allowed.

This is covered by defect report 363: Initialization of class from self which says:

And if so, what is the semantics of the self-initialization of UDT? For example

 #include <stdio.h>

 struct A {
        A()           { printf("A::A() %p\n",            this);     }
        A(const A& a) { printf("A::A(const A&) %p %p\n", this, &a); }
        ~A()          { printf("A::~A() %p\n",           this);     }
 };

 int main()
 {
  A a=a;
 }

can be compiled and prints:

A::A(const A&) 0253FDD8 0253FDD8
A::~A() 0253FDD8

and the resolution was:

3.8 [basic.life] paragraph 6 indicates that the references here are valid. It's permitted to take the address of a class object before it is fully initialized, and it's permitted to pass it as an argument to a reference parameter as long as the reference can bind directly. Except for the failure to cast the pointers to void * for the %p in the printfs, these examples are standard-conforming.

The full quote of section 3.8 [basic.life] from the draft C++14 standard is as follows:

Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see 12.7. Otherwise, such a glvalue refers to allocated storage (3.7.4.2), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if:

  • an lvalue-to-rvalue conversion (4.1) is applied to such a glvalue,

  • the glvalue is used to access a non-static data member or call a non-static member function of the object, or

  • the glvalue is bound to a reference to a virtual base class (8.5.3), or

  • the glvalue is used as the operand of a dynamic_cast (5.2.7) or as the operand of typeid.

We are not doing anything with foo that falls under undefined behavior as defined by the bullets above.

If we try this with Clang, we see an ominous warning (see it live):

warning: variable 'foo' is uninitialized when used within its own initialization [-Wuninitialized]

It is a valid warning since producing an indeterminate value from an uninitialized automatic variable is undefined behavior. However, in this case you are just binding a reference and taking the address of the variable within the constructor, which does not produce an indeterminate value and is valid. On the other hand, the following self-initialization example from the draft C++11 standard:

int x = x ;

does invoke undefined behavior.

Active issue 453: References may only bind to “valid” objects also seems relevant but is still open. The initial proposed language is consistent with Defect Report 363.

4
  • Ah, ok :) (Somehow I didn't think about that and took it for granted.) Nevertheless, I think there's a small detail missing in the Standard.
    – dyp
    Commented Sep 16, 2015 at 12:47
  • @dyp: It's indeed not precisely specified, but it must be ordered before the first base class constructor starts executing. You just can't determine how much before.
    – MSalters
    Commented Sep 16, 2015 at 12:54
  • 3
    Thanks Shafik! The people hanging out on Stack Overflow, and the ability of the site to put the right questions in front of the right eyes never ceases to amaze me! Commented Sep 16, 2015 at 12:55
  • Sorry, I was talking about the Original Post / the question. Anyway, thinking about it again, I might have misunderstood the "constructed" part. I thought OP meant we're passing a constructed object into the constructor for that object, whereas in fact we're passing an uninitialized object into the constructor.
    – dyp
    Commented Sep 24, 2015 at 9:47
16

The constructor is called at a point where memory is allocated for the object-to-be. At that point, no object exists at that location (or possibly an object with a trivial destructor). Furthermore, the this pointer refers to that memory and the memory is properly aligned.

Since it's allocated and aligned memory, we may refer to it using lvalue expressions of Foo type (i.e. Foo&). What we may not yet do is have an lvalue-to-rvalue conversion. That's only allowed after the constructor body is entered.

In this case, the code just tries to print &bar inside the constructor body. It would even be legal to print bar.member here. Since the constructor body has been entered, a Foo object exists and its members may be read.

This leaves us with one small detail, and that's name lookup. In Foo foo(foo), the first foo introduces the name in scope and the second foo therefore refers back to the just-declared name. That's why int x = x is invalid, but int x = sizeof(x) is valid.

2
  • But I didn't get any error while compiling int x = x with g++ 4.8. Invalid statement should spit error, right?
    – cbinder
    Commented Sep 23, 2015 at 5:24
  • @cbinder: Should, but unfortunately not will.
    – MSalters
    Commented Sep 23, 2015 at 6:53
0

As said in other answers, an object can be initialized with itself as long as you do not use its values before they are initialized. You can still bind the object to a reference or take its address. But beyond the fact that it is valid, let's explore a usage example.

The example below might be controversial, you can surely propose many other ideas for implementing it. And yet, it presents a valid usage of this strange C++ property, that you can pass an object into its own constructor.

class Employee {
   string name;
   // manager may change so we don't hold it as a reference
   const Employee* pManager; 
public:
  // we prefer to get the manager as a reference and not as a pointer
  Employee(std::string name, const Employee& manager)
    : name(std::move(name)), pManager(&manager) {}

  void modifyManager(const Employee& manager) {
      // TODO: check for recursive connection and throw an exception
      pManager = &manager;
  }

  friend std::ostream& operator<<(std::ostream& out, const Employee& e) {
      out << e.name << " reporting to: ";
      if(e.pManager == &e)
        out << "self";
      else
        out << *e.pManager;
      return out;
  }
};

Now comes the usage of initializing an object with itself:

// it is valid to create an employee who manages itself
Employee jane("Jane", jane);

In fact, with the given implementation of class Employee, the user has no other choice but to initialize the first Employee ever created, with itself as its own manager, as there is no other Employee yet that can be passed. And in a way that makes sense, as the first employee created should manage itself.

Code: http://coliru.stacked-crooked.com/a/9c397bce622eeacd

Not the answer you're looking for? Browse other questions tagged or ask your own question.