【发布时间】:2015-10-22 13:09:07
【问题描述】:
我有一个指向我想放入字符串中的一些数据的指针。我认为使用std::copy 应该是最安全的方法。
但是,在 Visual Studio 2010 中我收到警告
警告 C4996:“std::_Copy_impl”:带有可能不安全参数的函数调用 - 此调用依赖于调用者检查传递的值是否正确。要禁用此警告,请使用 -D_SCL_SECURE_NO_WARNINGS。
当然警告是正确的。在MSDN checked_array_iterator 上描述了一些checked_array_iterator 对象,它们可用于包装这样的指针并使其与STL 迭代器兼容。
问题是,这个checked_array_iterator 只能用作目标,不能用作源。
所以当我尝试这样使用它时,应用程序崩溃或无法编译:
char buffer[10] = "Test";
std::string s;
// These are parameters from an external call and only shown here to illustrate the usage.
char *pTargetAdress = &s;
const char *oBegin = buffer;
const char *oEnd = oBegin+sizeof(buffer);
std::string *p = reinterpret_cast<std::string *>(pTargetAdress);
std::copy(oBegin, oEnd, p->begin()); // crash
stdext::checked_array_iterator<const char *>beg(oBegin, oEnd-oBegin);
stdext::checked_array_iterator<const char *>end(oEnd, 0);
std::copy(beg, end, p->begin()); // crash
stdext::checked_array_iterator<const char *>v(oBegin, oEnd-oBegin);
std::copy(v.begin(), v.end(), p->begin()); // doesn't compile
如果有可移植的标准方式,我宁愿使用它而不是在 MS 扩展上使用。
【问题讨论】:
-
肯定有一个
string::assign可以将你的缓冲区作为参数,有或没有缓冲区大小。 -
@BoPersson,是的,你是对的。这就是我现在使用的。