vs2013 error:C4996

     在學習如何編寫移動構造函數的時候,照着文中的代碼敲,用vs013編譯,出現 error C4996: 'std::_Copy_impl': 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'

解決辦法如下:

方法一:
在出現該錯誤的文件中添加:#pragma warning(disable : 4996)     不理它
注意:1)添加位置:在包含頭文件語句前添加該語句;
          2)#pragma warning(disable:4996)只對當前文件(包括包含了當前文件的文件)起作用,並非對整個工程 。

方法二:
在包含頭文件語句前添加:#define _SCL_SECURE_NO_WARNINGS

方法三:
加入預處理器(項目屬性--C/C++--預處理--預處理定義)
_SCL_SECURE_NO_WARNINGS

方法四:
修改代碼:
	// 拷貝構造函數
	MemoryBlock(const MemoryBlock& other)
		:_length(other._length)
		, _data(new int[other._length])
	{
		std::copy(other._data, other._data + _length, stdext::checked_array_iterator<int*>(_data,_length)/*_data*/);
		std::cout << "Copy Constructor" << std::endl;
	}


原因:
     不安全的函數,象vector的下標操作算子,如果不恰當的調用,通常會導致不明確的行爲。爲了保護你的發行版本的應用程序,Visual C++2005便引入了_SECURE_SCL符號,用來給那些非安全的函數添加運行時檢查。
     如果_SECURE_SCL定義爲1,不安全的參數使用會造成error,程序終止。如果定義爲0,禁用“經檢查的迭代器”(checked iterators:Checked iterators ensure that the bounds of your container are not overwritten.)。默認情況下,_SECURE_SCL在release版是0,在debug版是1。
     以上述代碼中的std::copy(first, last, destination)爲例;其中,first和last是定義拷貝範圍的迭代參數,destination是輸出迭代參數,指示了目標緩衝區的位置。這裏有一個潛在危險是destination所對應的目標緩衝區或容器不足夠大,無法容納所要拷貝的元素。如果Destination是一個需要安全檢查的迭代參數,類似的錯誤將被捕獲。但是,這僅僅是一個假設。如果destination是一個簡單的指針,將無法保證copy運算函數正確運轉。
     相對而言,方法四更安全,前三種方法只是忽略了這種潛在危險。

關於checked iterators的擴展閱讀,可參考:

-------------------------------------------------
參考資料:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章