原測試代碼如下:
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