关于C++中的复制控制

About copy control in C++

本文关键字:复制 控制 C++ 关于      更新时间:2023-10-16

我定义了一个名为Student的类。

// Student.h
#pragma once
#include <iostream>
using namespace std;
class Student {
public:
    Student();
    Student(const Student &s);
    Student(int ii);
    Student& operator=(const Student &s);
    ~Student();
private:
    int i;
};
// Student.cpp
#include "Student.h"
Student::Student(): i(0)
{
    cout << "ctor" << endl;
}
Student::Student(const Student &s)
{
    i = s.i;
    cout << "copy constructor" << endl;
}
Student::Student(int ii): i(ii)
{
    cout << "Student(int ii)" <<  endl;
}
Student& Student::operator=(const Student &s)
{
    cout << "assignment operator" << endl;
    i = s.i;
    return *this;
}
Student::~Student()
{
}
// main.cpp
#include <vector>
#include "Student.h"
int main()
{
    vector<Student> s(5);
    system("pause");
    return 0;
}

我在Visual Studio 2015上运行了此程序。
输出结果:

ctor  
ctor  
ctor  
ctor  
ctor  

但我预计结果是:

ctor  
copy constructor  
copy constructor  
copy constructor  
copy constructor  
copy constructor  

我错了吗?此外,我写道:

Student s1;
Student s2 = s1;

输出结果:

ctor  
copy constructor  

而不是:

ctor  
copy constructor  
copy constructor  

正如C++引物(第四版)在第13章中所说。

第三个,当我写道:

Student s = 3;

输出结果:

Student(int ii)

我认为这个应该是:

Student(int ii)  
copy constructor  

如果您查阅std::vector::vector(size_type count)上的文档,您会看到

构造包含count个默认插入的T实例的容器。不进行复制。

所以您只会看到构造函数调用。

中的第二个

Student s1;
Student s2 = s1;

s2 = s1没有使用赋值运算符,而是使用复制初始化。这使用复制构造函数来构造字符串。

在你的第三个例子

Student(int ii)  
copy constructor  

将是有效的输出。你没有得到这一点的原因是编译器很聪明,它可以省略副本,并使用使用int的构造函数直接构造s,而不是创建一个临时Student然后制作副本。