Home > Backend Development > C++ > Can You Pass an Object to Its Own Constructor in C ?

Can You Pass an Object to Its Own Constructor in C ?

Linda Hamilton
Release: 2024-11-11 00:36:02
Original
635 people have browsed it

Can You Pass an Object to Its Own Constructor in C  ?

Can Objects Be Passed into Their Own Constructors?

Question:

Within a C class's constructor, is it acceptable to pass an object as an argument to itself?

Answer:

Surprisingly, passing an object into its own constructor is permitted under the C standard, despite appearing unconventional. This is explained by defect report 363, which states that an uninitialized object can be used to bind references and take addresses.

Explanation:

Section 3.8 of the C 14 standard clarifies that before an object's lifetime begins or ends, any glvalue referencing the object can be used but only for limited purposes. This includes binding references and taking addresses, which do not depend on the object's value.

Practically speaking, using an uninitialized object in a constructor can lead to warnings, as demonstrated by Clang's warning about "uninitialized" variables. However, these warnings do not indicate undefined behavior since no indeterminate values are being produced.

An example that does result in undefined behavior is self-initialization with an assignment, such as "int x = x".

Conclusion:

While passing objects into their own constructors may seem unusual, it is a valid practice under the C standard, allowing for limited interactions with uninitialized objects during the construction process.

The above is the detailed content of Can You Pass an Object to Its Own Constructor in C ?. 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