gpt4 book ai didi

c++ - 关于 C++ 中的复制控制

转载 作者:搜寻专家 更新时间:2023-10-30 23:54:59 25 4
gpt4 key购买 nike

我定义了一个名为 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++ primer(第四版)第13章所说。

第三个,我写的时候:

Student s = 3;

输出结果:

Student(int ii)

我觉得这个应该是:

Student(int ii)  
copy constructor

最佳答案

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

Constructs the container with count default-inserted instances of T. No copies are made.

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

其次

Student s1;
Student s2 = s1;

s2 = s1 没有使用赋值运算符,而是使用了 copy initialization .这使用复制构造函数来构造字符串。

在你的第三个例子中

Student(int ii)  
copy constructor

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

关于c++ - 关于 C++ 中的复制控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34295378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com