原测试代码如下:
int main() {vector<int>v1{1,3,5,7,9,2,4,6,8};allocator<int>alloc;auto data = alloc.allocate(9);uninitialized_copy(v1.begin(),v1.end(), data);auto end = data + 9;while(data!=end) {cout << *data <<" ";data++;}cout << endl;system("pause");return 0;
}
运行后报错界面如下:
1>------ 已启动生成: 项目: ConsoleApplication1, 配置: Debug Win32 ------
1> test2.cpp
1>e:\0000softwareinstall\visualstudio\vc\include\xmemory(350): error C4996: 'std::_Uninitialized_copy0': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
1> e:\0000softwareinstall\visualstudio\vc\include\xmemory(336): note: 参见“std::_Uninitialized_copy0”的声明
1> e:\study\c++\primer练习程序\consoleapplication1\consoleapplication1\test2.cpp(10): note: 参见对正在编译的函数 模板 实例化“_FwdIt std::uninitialized_copy<std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>,int*>(_InIt,_InIt,_FwdIt)”的引用
1> with
1> [
1> _FwdIt=int *,
1> _InIt=std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>
1> ]
在其头部加#define _SCL_SECURE_NO_WARNINGS
,即可运行成功
#define _SCL_SECURE_NO_WARNINGS
#include<vector>
# include<iostream>
using namespace std;int main() {vector<int>v1{ 1,3,5,7,9,2,4,6,8 };allocator<int>alloc;auto data = alloc.allocate(9);uninitialized_copy(v1.begin(), v1.end(), data);auto end = data + 9;while (data != end) {cout << *data << " ";data++;}cout << endl;system("pause");return 0;
}
输出结果为:
1 3 5 7 9 2 4 6 8
即,我们将v1中的数据拷贝到了以data为起始地址的内存中
测试代码二:
#define _SCL_SECURE_NO_WARNINGS
#include<vector>
# include<iostream>
using namespace std;int main() {vector<int>v1{ 2,4 };vector<int>v2{ 1,3,5,7,9,2,4,6,8 };uninitialized_copy(v1.begin(), v1.end(), v2.begin());for (auto a:v2) {cout << a << " ";}cout << endl;system("pause");return 0;
}
输出结果:
2 4 5 7 9 2 4 6 8