简体   繁体   English

Netbeans在c ++中创建了一个默认构造函数。 它有什么作用?

[英]Netbeans created a default constructor in c++. What does it do?

Netbeans created this default constructor. Netbeans创建了此默认构造函数。 I was curious what is its purpose. 我很好奇它的目的是什么。 I don't know what to call it, or what it does. 我不知道该怎么称呼它,或者它做什么。 It more of a curiosity. 更有好奇心。 My only thought was maybe cloning? 我唯一的想法也许是克隆? something tells me I am wrong. 某事告诉我我错了。

#ifndef     FOO_H
#define FOO_H

class Foo {
public:
    Foo();
    Foo(const Foo& orig);
    virtual ~Foo();
private:

};

Yes Netbeans has kindly created explicitly created the default and copy constructors. 是的,Netbeans友好地创建了显式创建的默认构造函数和复制构造函数。

It has also supplied you a virtual destructor to help you avoid memory leaks when inheriting from this class (Consider BabyFoo to be a child class of Foo): if you write Foo* foo = new BabyFoo(); delete foo; 它还提供了一个虚拟析构函数,以帮助您避免从此类继承时发生内存泄漏(将BabyFoo视为Foo的子类):如果您编写Foo* foo = new BabyFoo(); delete foo; Foo* foo = new BabyFoo(); delete foo; then you'll leak memory as the member data in BabyFoo will not be deleted unless Foo has a virtual destructor. 那么您将泄漏内存,因为除非Foo具有虚拟析构函数,否则BabyFoo中的成员数据将不会被删除。

I don't like the way Netbeans does this because: 我不喜欢Netbeans这样做的方式,因为:

1) I think that a copy constructor can be difficult to maintain (it's easy to forget to copy a newly added member datum) and is unnecessary to supply if your member data don't need to be explicitly copied (bare pointer data would probably need to be explicitly copied). 1)我认为复制构造函数可能很难维护(很容易忘记复制新添加的成员数据),并且如果不需要显式复制成员数据(可能需要使用裸指针数据),则不需要提供复制构造函数明确复制)。 The one automatically generated by the compiler will (shallow) copy all member data. 由编译器自动生成的将(浅)复制所有成员数据。

2) A virtual destructor introduces a virtual function pointer table into your class which is an overhead. 2)虚拟析构函数将虚拟函数指针表引入您的类,这是一项开销。

3) Acknowledge Oli Charlesworth's comment: http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) 3)确认Oli Charlesworth的评论: http : //en.wikipedia.org/wiki/Rule_of_three_(C% 2B%2B_programming

Foo(const Foo& orig); 

This is copy constructor, every class has aa default copy constructor which is provided by the compiler 这是复制构造函数,每个类都有一个由编译器提供的默认复制构造函数

there purpose is to create a copy of an existing object 目的是创建现有对象的副本

Refer http://en.wikipedia.org/wiki/Copy_constructor for more details about copy constructor 有关复制构造函数的更多详细信息,请参见http://en.wikipedia.org/wiki/Copy_constructor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM