【问题标题】:class object as vector element , destructor getting called too many times类对象作为向量元素,析构函数被调用太多次
【发布时间】:2016-04-08 18:01:10
【问题描述】:
#include <vector>
#include <iostream>
#include <memory>

using namespace std;

class A
{
    static int k;
    public:
    A(){k++ ; cout << "constructor : " <<k<< endl;};
    ~A(){k--; cout << "destructor : "  << k <<endl;};
    void show() { cout<<"current value of k = "<<k<<endl; }
};
int A::k = 0;
int main( )
{
    vector<A> test;
    test.push_back(A());
    test.emplace(test.end(), A()); 
    test[0].show();
    cout<<test.size()<<endl;
    return 0; 
}

输出:

构造函数:1

析构函数:0

构造函数:1

析构函数:0

析构函数:-1

k 的当前值 = -1

2

析构函数:-2

析构函数:-3

为什么析构函数被调用了太多次,因为构造函数只被调用了两次,所以它应该只被调用两次?如何避免这种情况?

【问题讨论】:

  • 当您调用emplace 时,您应该将参数提供给类构造函数,而不是类的实例。
  • @Sean 没有错。该实例将传递给复制构造函数。与替代方案相比,它可能效率稍低,但不是错误。

标签: c++ destructor


【解决方案1】:

正在使用编译器生成的复制构造函数,它不会增加 k。

在您的源代码中明确包含它,一切都会好起来的。

【讨论】:

    【解决方案2】:

    您正在制作副本,但您的跟踪输出没有显示(并且您的 k 在发生时不会增加)。所以“额外的”析构函数调用与复制构造一起使用。

    您可以正确使用emplace 删除其中一个副本:

    test.emplace(test.end());
    //                     ^ no A() here; that would be like doing test.push_back(A(A()))
    

    但您在 push_back 本身中仍有一份副本。

    编写一个复制构造函数,以便您的跟踪输出说明这些操作:

    A(const A&) { k++; cout << "copy-constructor : " << k << endl; }
    

    (我不会打扰移动构造函数,如that'll delete the copy assignment operator and all hell will break loose。)


    完成的代码:

    #include <vector>
    #include <iostream>
    #include <memory>
    
    using namespace std;
    
    class A
    {
        static int k;
    
    public:
        A()         { k++; cout << "constructor : "      << k << endl; }
        ~A()        { k--; cout << "destructor : "       << k << endl; }
        A(const A&) { k++; cout << "copy-constructor : " << k << endl; }
    
        void show() { cout << "current value of k = " << k << endl; }
    };
    
    int A::k = 0;
    
    int main()
    {
        vector<A> test;
    
        test.push_back(A());
        test.emplace(test.end(), A());
    
        test[0].show();
        cout << test.size() << endl;
    }
    

    输出:

    constructor : 1
    copy-constructor : 2
    destructor : 1
    constructor : 2
    copy-constructor : 3
    copy-constructor : 4
    destructor : 3
    destructor : 2
    current value of k = 2
    2
    destructor : 1
    destructor : 0
    

    (live demo)

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 2021-09-03
      • 2014-05-27
      • 2015-02-25
      • 2021-09-24
      • 2019-12-16
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多