c++primer 中的一個函數報錯的問題
StrVec類的設計中定義這個類,定義了一個static變量alloc,用來分配內存和構造元素
class StrVec
{
public:
StrVec() :elements(nullptr), first_free(nullptr), cap(nullptr) {}
StrVec(initializer_list<string> li);
StrVec(const StrVec&);
StrVec& operator= (const StrVec&);
~StrVec();
void push_back(const string&); // 拷貝元素
size_t size() const { return first_free - elements; }
size_t capacity() const { return cap - elements; }
string *begin() const{ return elements; }
string *end() const { return first_free; }
void reserve(size_t n);
void resize(size_t n);
void resize(size_t n, string str);
private:
static allocator<string> alloc; // 靜態成員,分配
pair<string*, string*> alloc_n_copy(const string*, const string*); // 分配內存,拷貝元素
在實現函數alloc_n_copy的時候
pair<string *, string*> StrVec::alloc_n_copy(const string *b, const string *e)
{
auto data =alloc.allocate(e - b);
return{ data,uninitialized_copy(b,e,data) };
}
在調用uinitialized_copy函數時,會產生不安全的警告:
錯誤 C4996 'std::uninitialized_copy::_Unchecked_iterators::_Deprecate': Call to 'std::uninitialized_copy' 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'
對參數的調用可能不安全,需要調用這個函數的函數來保證迭代器的值是正確的。程序會報錯。
去掉static聲明,加上宏命令#define _SCL_SECURE_NO_WARNINGS(.cpp文件中)可以去掉這個警告