Home > Backend Development > C++ > Can You Construct a C Object Using Itself as an Argument?

Can You Construct a C Object Using Itself as an Argument?

Mary-Kate Olsen
Release: 2024-11-10 18:45:02
Original
731 people have browsed it

Can You Construct a C   Object Using Itself as an Argument?

Passing a C Object into Its Own Constructor: Is It Legal?

It may seem surprising to discover that constructing an object from itself in C is indeed permitted. The following code demonstrates this unexpected behavior:

#include <iostream>

struct Foo {
    Foo(Foo& bar) {
        std::cout << &bar << std::endl;
    }
};

int main(int argc, char** argv) {
    Foo foo(foo); // This works!
    std::cout << &foo << std::endl; // And this works too...
}
Copy after login

In this code, an object of type Foo is passed as an argument to its own constructor. This might appear to be a circular definition, but the C standards actually allow it.

Despite the object foo being uninitialized, the code manipulates it in a manner permitted by the standard. Specifically, before an object is fully initialized, binding a reference to it or taking its address is allowed.

This behavior is further explained in defect report 363, which concludes that references are valid and that it is permissible to take the address of a class object before it is fully initialized and provide it as a reference parameter.

While it may be unusual or impractical to utilize this behavior, it provides insights into the inner workings of classes and the limited ways in which an uninitialized object can be manipulated.

The above is the detailed content of Can You Construct a C Object Using Itself as an Argument?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template