C ++基本构造函数/向量问题(1个构造函数,2个析构函数) [英] C++ basic constructors/vectors problem (1 constructor, 2 destructors)

查看:141
本文介绍了C ++基本构造函数/向量问题(1个构造函数,2个析构函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题可能是基本的,但不能找出什么是错误的(它导致在我的应用程序的大量memleaks):

  class MyClass {
public:
MyClass(){cout< constructor(); \\\
; };
MyClass operator =(const MyClass& b){
cout<< operator =; \\\
; return MyClass();
};
〜MyClass(){cout<< destructor(); \\\
; };
};

main(){
cout<< 1 \\\
;
vector< MyClass>一个;
cout<< 2 \\\
;
MyClass b:
cout<< 3 \\\
;
a.push_back(b);
cout<< 4 \\\
;
}

输出是:

  1 
2
constructor();
3
4
destructor();
destructor();




  1. 为什么有2个析构函数?

  2. 如果是因为创建了要插入到向量中的副本,那么operator =从不调用?


当b对象被推入向量时,会产生一个副本,但不能由 operator =()你有 - 使用编译器生成的复制构造函数。



当main()超出范围时, b object被销毁,并且向量中的副本被销毁。



添加一个显式副本构造函数,以查看:

  MyClass(MyClass const& other){
cout< copy ctor\\\
;
};


Question is probably pretty basic, but can't find out what's wrong (and it leads to huge of memleaks in my app):

class MyClass {
public:
    MyClass() { cout << "constructor();\n"; };
    MyClass operator= (const MyClass& b){ 
        cout << "operator=;\n"; return MyClass(); 
    };
    ~MyClass() { cout << "destructor();\n"; };
};

main() {
	cout << "1\n";
	vector<MyClass> a;
	cout << "2\n";
	MyClass b;
	cout << "3\n";
	a.push_back(b);
	cout << "4\n";
}

The output is:

1
2
constructor();
3
4
destructor();
destructor();

  1. Why are there 2 destructors?
  2. If it's because a copy is created to be inserted into vector - how come "operator=" is never called?

解决方案

When the b object gets pushed onto the vector a copy is made, but not by the operator=() you have - the compiler generated copy constructor is used.

When the main() goes out of scope, the b object is destroyed and the copy in the vector is destroyed.

Add an explicit copy constructor to see this:

MyClass( MyClass const& other) {
    cout << "copy ctor\n";
};

这篇关于C ++基本构造函数/向量问题(1个构造函数,2个析构函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆