为什么在下面的代码中在向量中打印值之前调用析构函数

时间:2018-02-28 22:43:50

标签: c++ vector destructor

在以下代码中,向量在调用print方法之前丢失了所有内容。 我假设在print语句之前调用析构函数。 任何人都可以告诉我为什么在对象超出范围之前调用析构函数。

    #include<iostream>
    #include <vector>
    using namespace std;
        class test {
        private:
            vector<int> distance;
        public:
            test();
            void print();
        };
        void test::print() {
            cout << "In Print";
            for (auto itr = distance.begin(); itr != distance.end(); ++itr)
                cout << *itr << "\n";
        }
        test::test() {
            std::vector<int>distance(100, 1);
        }
        int main()
        {
            cout << "executing main \n";
            test t;
            t.print();
            cin.get();
            return 0;
        }

2 个答案:

答案 0 :(得分:4)

test::test() {
    std::vector<int>distance(100, 1);
}

这将在构造函数的本地创建一个新的向量,一旦构造函数完成就会被销毁。

要初始化班级中的向量,您应该使用initializer list

test::test() : distance(100,1) {}

修改

另一种选择是在类定义中初始化向量。

#include<iostream>
#include <vector>
using namespace std;
    class test {
    private:
        vector<int> distance{5, 7, 9, 12};
    public:
        test();
        void print();
    };
    void test::print() {
        cout << "In Print";
        for (auto itr = distance.begin(); itr != distance.end(); ++itr)
            cout << *itr << "\n";
    }
    int main()
    {
        cout << "executing main \n";
        test t;
        t.print();
        cin.get();
        return 0;
    }

答案 1 :(得分:0)

<强>解

在构造函数中初始化成员向量的正确方法是:

test::test()
: distance(100, 1) // initializes member vector with 100 ones, but
                   // you may use any vector constructor here
{
}

这也有效:

test::test()
: distance() // this line is implicit if you don't add it
{
    for (auto i = 0; i < 100; ++i) {
        distance.push_back(1); // appends 1 to the member distance
    }
}

但它不可取,因为它的效率较低,因为您创建并初始化默认的空向量,然后在构造函数的主体中再次初始化它。但是,根据您需要初始化向量的内容,例如,如果值需要计算,则可以在构造函数的主体中执行此操作。

有关std :: vector&lt;&gt;的良好参考,包括其构造函数,请参阅cppreference.com。我写的这个矢量教程也可能有用:C++ std::vector for post-beginners

您的问题

您的构造函数正在创建一个新的不同的向量,其主体中具有相同的名称。然后,当析构函数完成时,在那里初始化的新向量超出范围,并且它被销毁:

test::test()
{
    vector<int> distance(100, 1); // Creates a new vector with the same
                                  // name as your member variable.
} // end of constructor scope; the vector created here is destroyed

上面的构造函数相当于:

test::test()
: distance() // default initialization of member distance
{
    vector<int> distance(100, 1); // Creates a new different vector with the
                                  // same name as your member variable.
} // end of constructor scope; the new vector created is destroyed