关于C++中的复制控制
About copy control in C++
我定义了一个名为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
然后制作副本。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 使用strcpy将char数组的元素复制到另一个数组
- 是否可以初始化不可复制类型的成员变量(或基类)
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 复制列表初始化的隐式转换的等级是多少
- 当从函数参数中的临时值调用复制构造函数时
- 有可能在Armadillo中复制MATLAB circshift方法吗
- 控制允许动态运行c++的并发操作数
- 从控制台中删除最后打印的元素
- 复制几乎为空的数组的最快方法
- 以下示例中如何避免代码复制?C++/库达
- 是否可以使用if constexpr删除控制流语句
- 如何控制将返回对象复制到新对象中
- 关于C++中的复制控制
- 我可以在C++中控制复制到CPU缓存中的内容吗
- C++:如果我不使用 move,我还需要关心复制控制吗?
- c++复制控制问题
- 为什么不通过std::cin复制并粘贴到控制台中读取会产生与从std::ifstream读取相同的结果呢