How to return value of std::copy in case of success or failure?

北城以北 提交于 2019-12-10 13:17:12

问题


I am using std::copy to copy the objects in std::deque to a file. The code is working fine but I need to check if copying was successful and accordingly I need to set the flag or else throw exception.

I have googled but could not find the solution how to check if std::copy has successfully copied the values into the file.

Could someone please throw a light on it.


回答1:


If writing to the file fails, then the file stream's error flags will be set - you can either check these after the copy, or call the exceptions member function first to make it throw an exception on error. If anything else fails, then an exception will be thrown.




回答2:


AFAIK std::copy algorithm doesn't check anything and just iterates over all elements and copies them to output iterator. This means that you should provide enought space in output iterator yourself otherwise the behaviour is unspecified.

So in your case you should yourself check that the output file is writable, etc.. One of possible ways to check this I think use error flags for the file stream you're using, i.e. after copying check that your ofstream is good (you can use good(), eof(), fail() and bad() functions for this).

The second approach is to check the return value of std::copy. As it returns an iterator to the end of the destination range (which points to the element following the copy of last) then you can calculate the difference between the return value of std::copy and your output iterator and make sure that its equal to the size of your deque. E.g. (pseudocode)

OutputIterator result = std::copy(input.begin(), input.end(), output);
assert(result - output == input.end() - input.begin());

EDIT: The second approach works only when output is also input iterator type, so std::distance to work for it. It will be more correct to write:

assert(std::distance(output, result) == std::distance(input.begin(), input.end()));


来源:https://stackoverflow.com/questions/9681702/how-to-return-value-of-stdcopy-in-case-of-success-or-failure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!