Home > Backend Development > C++ > Why Isn't the Copy Constructor Called When Assigning to an Existing Object in C ?

Why Isn't the Copy Constructor Called When Assigning to an Existing Object in C ?

DDD
Release: 2024-12-08 09:22:11
Original
582 people have browsed it

Why Isn't the Copy Constructor Called When Assigning to an Existing Object in C  ?

Why Copy Constructor is Bypassed When Assigning a New Value to an Existing Object

In the provided code snippet, an object a is initialized with the value 5. The standard A constructor is invoked as expected. However, contrary to assumptions, the copy constructor is not called when assigning the newly constructed object.

This behavior is neither the result of compiler optimization nor an omission in the language specification. It is explicitly documented in the C standard (§12.8.15, pg. 211). The standard states that "it is completely acceptable" for the following assignments to be semantically equivalent:

T = x;
T(x);
Copy after login

It logically follows that a redundant assignment like T(T(x)) can be removed from the code optimization. Therefore, the compiler automatically invokes the default constructor to initialize a and then directly assigns the newly constructed object.

To force the copy constructor to be invoked, one needs to explicitly default-construct a before assigning:

A a; // Default-construct 'a'

// Copy constructor will be called to
// copy data from the newly constructed object.
a = A(5);
Copy after login

The above is the detailed content of Why Isn't the Copy Constructor Called When Assigning to an Existing Object 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template