为什么在以下情况下会发生初始化?

Why does initialization happen in the following case?

我正在阅读这本书:“C++:完整参考”,4e。在copy constructors的题目中,写了以下内容:

It is important to understand that C++ defines two distinct types of situations in which the value of one object is given to another. The first is an assignment. The second is an initialization, which can occur in any of the three ways:

  1. When one object explicitly initializes another, such as in declaration. E.g. myClass x = y;
  2. When a copy of an object is made to be passed to a function. E.g. func(y); // where y is an object of some class.
  3. When a temporary object is generated (most commonly, as a return value). E.g. y = func(); // y receiving a temporary, return object.

第一种和第二种情况我看得懂,第三种我看不懂

在第三种情况下,如果函数 returns 是一个临时对象,为什么 assignment 操作不会在 y[=25= 之间发生] 和临时对象?

初始化的必要性是什么?

如果所有初始化都在发生,它发生在哪里?我的意思是,正在初始化什么?

需要初始化临时对象,以便y可以赋值。

当你初始化时,这意味着你在创建时第一次给你的变量赋值。如果您分配,则意味着该对象之前已创建,现在被(重新)分配了一个值。

std::string name; *A variable is declared but not initialised*
std::string name = 'Sarah'; *The variable is initialised*
name = 'Lisa' *The variable is reassigned a value*

情况3,函数需要创建一个临时对象,该对象只存在于函数作用域内。然后它 returns 这个,如果没有另外定义,作为一个值。并且可以将值赋值给已有的y,或者y初始化,如果之前没有值

你需要记住,如果你想从现有对象创建新对象,你需要某种复制机制。这就是为什么我们需要一个复制构造函数:

Person peter = Person{'Peter'} *A new person named peter is created*
Person betterPeter = peter *You initalize newPeter with Peter*

那只会复制peter的地址。因此,如果您在 betterPeter 中进行任何更改,peter 将受到相同更改的影响。您想要的是拥有一个将所有元​​素从 peter 复制到 betterPeter 的函数。这并不难:https://en.cppreference.com/w/cpp/language/copy_constructor