STL Vector是否调用了未分配对象的析构函数?

Sup*_*alb 16 c++ stl vector

下面的代码显示了不期望的输出:

class test
{
    public:
    test()
    {
        std::cout << "Created" << (long)this << std::endl;
    }
    ~test()
    {
        std::cout << "Destroyed" << (long)this << std::endl;
    }
};

int main(int argc, char** argv)
{
    std::vector<test> v;
    test t;
    v.push_back(t);

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

执行时显示:

Created-1077942161
Destroyed-1077942161
Destroyed674242816
Run Code Online (Sandbox Code Playgroud)

我认为第二个"被摧毁"的输出不应该存在.当我不使用向量时,结果是一个Created和一个Destroyed行按预期方式.这种行为是否正常?

(这是在FreeBSD系统上使用GCC编译的)

Ker*_* SB 31

一切都因为它应该是:有局部变量t,它被创建,然后在年底销毁main(),并有v[0],它被创建并在结束时被销毁main().

您没有看到创建,v[0]因为这是由复制或移动构造函数发生的,而测试类没有提供.(因此编译器为您提供了一个,但没有输出.)


出于测试目的,一次性为自己编写包含所有可能的构造函数,析构函数,赋值和交换运算符的测试类并在每个编写器中打印诊断线是很方便的,因此您可以看到对象在容器和算法中使用时的行为方式.


Pra*_*ian 29

#include <cstdlib>
#include <vector>
#include <iostream>

class test
{
    public:
    test()
    {
        std::cout << "Created " << (long)this << std::endl;
    }
    test( const test& )
    {
        std::cout << "Copied " << (long)this << std::endl;
    }
    ~test()
    {
        std::cout << "Destroyed " << (long)this << std::endl;
    }
};

int main(int argc, char** argv)
{
    std::vector<test> v;
    test t;
    v.push_back(t);

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Created -1076546929
Copied 147865608
Destroyed -1076546929
Destroyed 147865608
Run Code Online (Sandbox Code Playgroud)

std::vector::push_back复制t对象,您可以看到上面代码调用的复制构造函数.