我定义了一个类来模拟Vector,这里有一些成员:
template<typename T>
class Vec {
public:
template<typename...Args>
void emplace_back(Args&&... args);
private:
std::pair<T*, T*> allocate_n_elements(const T*, const T*);
void check_if_full();
static std::allocator<T> admin;
T* beginp;
T* endp;
T* borderp;
};
template<typename T>
std::allocator<T> Vec<T>::admin;
template<typename T> inline
std::pair<T*, T*> Vec<T>::allocate_n_elements(const T* pbegin, const T* pend) {
auto newbeginp = admin.allocate(pend - pbegin);
return{ newbeginp, std::uninitialized_copy(pbegin, pend, newbeginp) };
}
template<typename T> inline
void Vec<T>::check_if_full() {
if (endp == borderp) {
reallocate();
}
}
template<typename T> inline
void Vec<T>::reallocate() {
auto newsize = size() ? size() * 2 : 1;
T* newbeginp = admin.allocate(newsize);
T* newendp = newbeginp;
T* old_index = beginp;
for (std::size_t i = 0; i != size(); ++i)
admin.construct(newendp++, std::move(*old_index++));
free();
beginp = newbeginp;
endp = newendp;
borderp = beginp + newsize;
}
template<typename T>
template<typename...Args>
inline void Vec<T>::emplace_back(Args&&...args) {
check_if_full();
admin.construct(endp++, std::forward<Args>(args)...);
}
要在VS2015上测试公共成员emplace_back(),我会错误地编写这样的代码:
Vec<std::string> vs;
vs.emplace_back("dsa",(10,'a'));
std::cout << vs[0];
令人惊讶的是,布置元素的打印方式如下:
dsa c:\ p r o g r a m f i l e s(x 8 6)\ m i s r o s t v s s a u s s t u d i
所以我很好奇为什么?哪些是“C:\ program ...”中的单词?