# 拷贝运算符和赋值运算符

以下是拷贝构造函数被调用的几种常见情况：

1. **直接初始化**： 当通过现有对象初始化新对象时，拷贝构造函数被调用。

   ```cpp
   MyClass obj1;
   MyClass obj2 = obj1; // 调用拷贝构造函数
   ```
2. **按值传递对象**： 当对象按值传递给函数时，拷贝构造函数被调用。

   ```cpp
   void func(MyClass obj) {
       // 拷贝构造函数被调用
   }

   int main() {
       MyClass obj;
       func(obj); // 传值调用函数，触发拷贝构造函数
   }
   ```
3. **按值返回对象**： 当函数按值返回对象时，拷贝构造函数被调用。不过，现代编译器通常会通过返回值优化（RVO）来避免实际的拷贝操作。

   ```cpp
   MyClass createObject() {
       MyClass obj;
       return obj; // 可能调用拷贝构造函数
   }

   int main() {
       MyClass obj = createObject(); // 可能调用拷贝构造函数
   }
   ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tysun.gitbook.io/c++/lei/kao-bei-yun-suan-fu-he-fu-zhi-yun-suan-fu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
