为什么编译器提供默认的复制构造函数

Why compiler provides default copy constructor(为什么编译器提供默认的复制构造函数)

本文介绍了为什么编译器提供默认的复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么编译器提供默认的复制构造函数.这个想法背后的策略是什么.

I wanted to know Why compiler provides default copy constructor..Whats the strategy behind that idea.

提前致谢.

推荐答案

来自一个相关(但不相同)的问题 - 为什么 C++ 编译器不定义 operator== 和 operator!=?:

From a related (but not same) question - Why don't C++ compilers define operator== and operator!=?:

Stroustrup 在The Design and Evolution of C++"(第 11.4.1 节 - 复制控制)中谈到了默认的复制构造函数:

Stroustrup said this about the default copy constructor in "The Design and Evolution of C++" (Section 11.4.1 - Control of Copying):

我个人认为很遗憾复制操作是默认定义的,并且我禁止复制我的许多类的对象.但是,C++ 继承了 C 的默认赋值和复制构造函数,并且经常使用.

I personally consider it unfortunate that copy operations are defined by default and I prohibit copying of objects of many of my classes. However, C++ inherited its default assignment and copy constructors from C, and they are frequently used.

所以答案是,Stroustrup 不情愿地包含它是为了与 C 向后兼容(可能是大多数 C++ 缺陷的原因,但也可能是 C++ 流行的主要原因).

So the answer is that it was included reluctantly by Stroustrup for backwards compatibility with C (probably the cause of most of C++'s warts, but also probably the primary reason for C++'s popularity).

出于我自己的目的,在我的 IDE 中,我用于新类的代码段包含私有赋值运算符和复制构造函数的声明,因此当我生成一个新类时,我不会得到默认的赋值和复制操作 - 我必须明确如果我希望编译器能够为我生成这些操作,请从 private: 部分删除这些操作的声明.

For my own purposes, in my IDE the snippet I use for new classes contains declarations for a private assignment operator and copy constructor so that when I gen up a new class I get no default assignment and copy operations - I have to explicitly remove the declaration of those operations from the private: section if I want the compiler to be able to generate them for me.

这篇关于为什么编译器提供默认的复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么编译器提供默认的复制构造函数

基础教程推荐