如何STL容器复制对象? [英] How do STL containers copy objects?
问题描述
我知道STL容器如向量
在添加对象时复制对象。 push_back
方法如下:
void push_back(const T& x) ;
我惊讶地发现它将该项目作为引用。我写了一个示例程序来看看它是如何工作的。
struct Foo
{
Foo b $ b {
std :: cout<< Inside Foo constructor< std :: endl;
}
Foo(const Foo& f)
{
std :: cout< inside copy constructor< std :: endl;
}
};
Foo f;
std :: vector< Foo> foos;
foos.push_back(f);
这样就复制了对象,我可以看到它正在调用 copy-constructor 。
我的问题是,当 push_back
将项目作为引用时,它如何调用复制构造函数?
任何想法... p>它可能使用placement
new
在其内部数组中就地构造对象。放置 new
不分配任何内存;它只是放置你指定的对象,并调用构造函数。语法是 new(address)Class(constructor_arguments)
。 复制构造函数 T :: T(T const&)
被调用以就地创建副本。类似这样的东西(简化):
模板< T&
void vector< T> :: push_back(T const& item){
//如果必要,调整大小
new(& d_array [d_size ++])T
}
注意 T
必须有一个复制构造函数为此工作。默认情况下(如果你什么都不做),它会免费获得一个。如果您明确定义它,则向量< T>
必须 public
才能工作。
这是GNU的libstdc ++的功能它,但我怀疑这将是非常有启发性。有一个分配器(向量
的第二个模板参数),这使它不那么直接。
I know STL containers like vector
copies the object when it is added. push_back
method looks like:
void push_back ( const T& x );
I am surprised to see that it takes the item as reference. I wrote a sample program to see how it works.
struct Foo
{
Foo()
{
std::cout << "Inside Foo constructor" << std::endl;
}
Foo(const Foo& f)
{
std::cout << "inside copy constructor" << std::endl;
}
};
Foo f;
std::vector<Foo> foos;
foos.push_back(f);
This copies the object and I can see it is calling copy-constructor.
My question is, when the push_back
takes item as reference, how it is calling copy-constructor? Or am I missing something here?
Any thoughts..?
It probably uses "placement new
" to construct the object in-place in its internal array. Placement new
doesn't allocate any memory; it just places the object where you specify, and calls the constructor. The syntax is new (address) Class(constructor_arguments)
.
The copy constructor T::T(T const &)
is called to create the copy in-place. Something like this (simplified):
template<T>
void vector<T>::push_back(T const &item) {
// resize if necessary
new (&d_array[d_size++]) T(item);
}
Note that T
must have a copy constructor for this to work. By default (if you do nothing), it gets one for free. If you define it explicitly, it must be public
for vector<T>
to work.
Here's how GNU's libstdc++ does it, but I doubt that it'll be very enlightening. There is an allocator (the second template argument to vector
) that makes it less straightforward.
这篇关于如何STL容器复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!