3

我从C++ 参考页面中遇到了这样的代码:

#include <algorithm>
#include <list>
#include <vector>
#include <functional>

int main()
{
    std::list<int> l = {-4, -3, -2, -1, 0, 1, 2, 3, 4};
    std::vector<std::reference_wrapper<int>> v(l.begin(), l.end());
    return 0;
}

这是“示例”部分的一个片段。代码按预期编译和运行。但怎么可能呢?std::reference_wrapper<int>不是默认可构造的。你怎么能把std::vector这些东西弄得一团糟?我一直把它想象std::vector成一个动态数组。但是你怎么能以这样的方式初始化操作系统新给你的一块内存呢?std::list

这听起来像是一个令人困惑的问题,但由于某种原因,我无法完全理解上面代码中发生的事情。里面发生了什么?

4

3 回答 3

6

It works because there's no default initialization there - the elements from the list are used to copy-initialize the vector.

The following, for example, wouldn't work:

std::vector<std::reference_wrapper<int>> v(42);
于 2013-08-22T14:11:48.880 回答
2

The constructor of std::vector<> first obtains a block of raw memory of appropriate size (using its allocator). It then constructs the objects. In case of the particular constructor here

template<typename It>
std::vector::vector(It begin, It end);

it constructs the elements from the valuetype of the iterators, thus each reference_wrapper<int> is constructed (in place) from an int.

于 2013-08-22T14:14:03.373 回答
1

向量中的所有对象都是使用带 int 的单参数构造函数构造的。这就是为什么您在语义上不需要默认构造函数的原因。

就实现而言,此行为可以通过使用而不是分配内存malloc来实现new(因此不会调用构造函数),然后new在将元素添加到向量时使用放置。

于 2013-08-22T14:16:01.557 回答