2

考虑下面的代码:为什么checked_array_iterator在VS2013中不包括<iterator>,但在VS2017中失败?

#include <memory> 
#include <locale> 

int main() { 
    auto source = std::make_unique<int[]>(16); 
    auto dest = std::make_unique<int[]>(16); 
    auto dp = stdext::checked_array_iterator<int*>(dest.get(), 16); 
    std::copy_n(source.get(), 16, dp); 
    return 0; 
} 

它通过运行cl.exe /EHsc <file>.cpp完全编译上的Visual Studio 2013。然而,在Visual Studio中2017年出现以下错误(等等)是由cl.exe抛出:

vc12.cpp(7): error C2653: 'stdext': is not a class or namespace name 
vc12.cpp(7): error C2065: 'checked_array_iterator': undeclared identifier 

为什么这个代码不再编译?

+0

的问题可能是很具体,但在大项目我花了相当长的时间才弄清楚为什么它在VS2013上编译,没有搜索引擎取得任何结果。 – Lennart

+1

顺便说一句,应该是'int main'。 'void main'不是可移植的C++。 –

+0

@BaummitAugen:是的,我尽量保持最小。将添加'int'和'return'。 – Lennart

回答

1

该示例缺少#include <iterator>。从技术上讲,Visual Studio 2013也缺少它(请参阅Why include what you use),但由于包含它的链条,它在那里工作。在Visual Studio 2013和Visual Studio 2017之间,包括std - 的页眉已经改版。

该示例显示#include <locale>。在旧版本中,#include <iterator>locale的包含链的一部分,在Visual Studio 2017中不再是这种情况。

但是,由于VS2017非常新,因此很难找到它的文档。重要文件可在doc.microsoft.com找到,它列出了所需的标题<iterator>

0

根据文档https://docs.microsoft.com/en-us/cpp/standard-library/checked-array-iterator-class包含在中但是您需要登录#include <iterator>

虽然不是为了纠正这个问题,但我会随同编写标准的一致性代码。做到这一点的最好方法是只使用静态分配的数组。这将允许你使用C++的beginendsize功能与它的工作:https://stackoverflow.com/a/33442842/2642059

有些情况下,这不会是一个很好的建议,如果动态数组是一个必须具备的,可以考虑使用vector。如果你无法忍受,然后使用unique_ptr的容器是做到这一点的好办法,但不是取决于checked_array_iterator喜欢保持自己的尺寸:

const size_t sourceSize = 16; 
auto source = std::make_unique<int[]>(sourceSize); 
auto dest = std::make_unique<int[]>(sourceSize); 
std::copy_n(source.get(), sourceSize, dest.get()) 
相关问题