#include <iostream>
#include <utility>
#include <vector>
int i = 0;
struct A
{
A() : j( ++i )
{
std::cout<<"constructor "<<j<<std::endl;
}
A( const A & c) : j(c.j)
{
std::cout<<"copy "<<j<<std::endl;
}
A( const A && c) : j(c.j)
{
std::cout<<"move "<<j<<std::endl;
}
~A()
{
std::cout<<"destructor "<<j<<std::endl;
}
int j;
};
typedef std::vector< A > vec;
void foo( vec & v )
{
v.push_back( std::move( A() ) );
}
int main()
{
vec v;
foo( v );
foo( v );
}
上面的示例产生下一个输出:
constructor 1
move 1
destructor 1
constructor 2
move 2
move 1
destructor 1
destructor 2
destructor 1
destructor 2
问题 :
- 为什么执行第一个析构函数(但没有为第二个对象执行)?
- 为什么第二个对象的移动在第一个对象的移动之前执行?
- 为什么最后每个对象执行两个析构函数?
PS我刚刚检查了,对象确实按预期放置(第一个到向量中的位置0,第二个到向量中的位置1)
PPS 如果重要的话,我使用的是 gcc 4.3,我像这样编译程序:
g++ n1.cpp -Wall -Wextra -pedantic -ansi -std=c++0x -O3