Pass an Object into Its Own Constructor in C
Some C programmers have discovered an intriguing behavior: passing an object into its own constructor. This raises questions about whether such a practice is legal or considered undefined behavior in C .
Consider the following code snippet:
#include <iostream> struct Foo { Foo(Foo& bar) { std::cout << &bar << std::endl; } }; int main() { Foo foo(foo); // Surprisingly, this compiles and executes std::cout << &foo << std::endl; }
In this code, the Foo constructor receives a reference to the constructed object itself before the object is fully initialized. Although the object is uninitialized, the code is allowed by the C standard.
Section 3.8 of the C 14 draft standard clarifies that before an object's lifetime begins (or after it ends), it is permitted to take its address or bind a reference to it as long as the reference can bind directly. Undefined behavior occurs only when certain operations, such as lvalue-to-rvalue conversions, accessing non-static data members, or virtual base class binding, are performed on such partially initialized objects.
The code example provided does not violate any of these restrictions. We are merely binding a reference and obtaining the address within the constructor, which is permitted.
Active issue 453, however, raises concerns about the validity of binding references to uninitialized objects. The initial proposed language supports Defect Report 363, which permits such binding as demonstrated in the code snippet.
While this behavior may appear odd initially, it is a result of the compiler allocating space for the object before initialization. This allows limited operations, such as reference binding and address retrieval, without producing indeterminate values.
The above is the detailed content of Can You Pass an Object into Its Own Constructor in C ?. For more information, please follow other related articles on the PHP Chinese website!