MST

星途 面试题库

面试题:C++ 拷贝构造函数参数传递的常见场景

请简述在 C++ 中,拷贝构造函数调用时,参数传递的常见场景有哪些,并举例说明。
16.8万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. 对象作为函数参数值传递
    • 场景描述:当一个对象以值传递的方式作为函数参数时,会调用拷贝构造函数。因为函数参数在栈上创建了一个新的对象副本。
    • 示例代码
#include <iostream>

class MyClass {
public:
    MyClass() { std::cout << "Constructor called" << std::endl; }
    MyClass(const MyClass& other) { std::cout << "Copy constructor called" << std::endl; }
};

void func(MyClass obj) {
    // 函数体
}

int main() {
    MyClass myObj;
    func(myObj);
    return 0;
}
  1. 函数返回对象
    • 场景描述:当函数返回一个对象时,如果返回值优化(RVO)没有生效,会调用拷贝构造函数来创建一个临时对象作为返回值。
    • 示例代码
#include <iostream>

class MyClass {
public:
    MyClass() { std::cout << "Constructor called" << std::endl; }
    MyClass(const MyClass& other) { std::cout << "Copy constructor called" << std::endl; }
};

MyClass func() {
    MyClass obj;
    return obj;
}

int main() {
    MyClass result = func();
    return 0;
}
  1. 用一个对象初始化另一个对象
    • 场景描述:在定义一个新对象并使用另一个同类型对象对其进行初始化时,会调用拷贝构造函数。
    • 示例代码
#include <iostream>

class MyClass {
public:
    MyClass() { std::cout << "Constructor called" << std::endl; }
    MyClass(const MyClass& other) { std::cout << "Copy constructor called" << std::endl; }
};

int main() {
    MyClass obj1;
    MyClass obj2 = obj1; // 这里调用拷贝构造函数
    return 0;
}
  1. 对象作为容器元素插入
    • 场景描述:当将对象插入到标准容器(如 std::vectorstd::list 等)中时,会调用拷贝构造函数,将对象拷贝到容器内部的存储位置。
    • 示例代码
#include <iostream>
#include <vector>

class MyClass {
public:
    MyClass() { std::cout << "Constructor called" << std::endl; }
    MyClass(const MyClass& other) { std::cout << "Copy constructor called" << std::endl; }
};

int main() {
    std::vector<MyClass> vec;
    MyClass obj;
    vec.push_back(obj);
    return 0;
}