关于C++中的复制控制

Nik*_*eng 2 c++ constructor

我定义了一个名为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;
}
Run Code Online (Sandbox Code Playgroud)

我在Visual Studio 2015上运行了这个程序.
输出结果:

ctor  
ctor  
ctor  
ctor  
ctor  
Run Code Online (Sandbox Code Playgroud)

但我希望结果如下:

ctor  
copy constructor  
copy constructor  
copy constructor  
copy constructor  
copy constructor  
Run Code Online (Sandbox Code Playgroud)

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

Student s1;
Student s2 = s1;
Run Code Online (Sandbox Code Playgroud)

输出结果:

ctor  
copy constructor  
Run Code Online (Sandbox Code Playgroud)

代替:

ctor  
copy constructor  
copy constructor  
Run Code Online (Sandbox Code Playgroud)

作为C++入门(第四版)在第13章中说过.

第三个,当我写道:

Student s = 3;
Run Code Online (Sandbox Code Playgroud)

输出结果:

Student(int ii)
Run Code Online (Sandbox Code Playgroud)

我认为这应该是:

Student(int ii)  
copy constructor  
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 7

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

使用计数默认插入的T实例构造容器.不创建副本.

所以你只会看到构造函数调用.

其次在

Student s1;
Student s2 = s1;
Run Code Online (Sandbox Code Playgroud)

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

在你的第三个例子中

Student(int ii)  
copy constructor  
Run Code Online (Sandbox Code Playgroud)

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