如何在 C++ 中测试向量初始化成功/失败
我有一个带有 vector
成员的 C++ 类,这些成员在构造函数中初始化为由构造函数的参数之一确定的大小。
summingBuffer = vector<float>(requiredSize);
如何检查向量构造函数是否已成功分配所需的空间?实例变量不是指针(应该是吗?),因此 if (NULL==myVector)
不起作用。 vector
是否会在分配错误时抛出异常?之后检查 .size()
怎么样?
谢谢...
I have a C++ class with vector<float>
members which are initialized in the constructor to a size determined by one of the constructor's arguments.
summingBuffer = vector<float>(requiredSize);
How do I check whether the vector constructor has successfully allocated the the required space? The instance vars aren't pointers (should they be?) so if (NULL==myVector)
doesn't work. Does vector
throw an exception on allocation error? How about checking .size()
afterwards?
Thank you...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认分配器在分配失败时抛出
std::bad_alloc
,就像new T
那样。所以,不需要,不需要检查尺寸。这不是C。Default allocator throws
std::bad_alloc
on failed allocation, just likenew T
does. So, no, no size checking is necessary. This isn't C.如果向量构造函数无法分配足够的存储空间,则会引发 bad_alloc,无需额外检查。
如果您不是绝对需要指针,那么使用指针并不是一个好主意。
另外,看起来您可以直接初始化向量,而不是使用构造函数的初始化列表来初始化向量。像这样的东西:
The vector constructor will raise
bad_alloc
if it couldn't allocate enough storage, no need for extra checks.Using pointers is not a good idea if you don't absolutely need them.
Also, looks like you could initialize your vectors directly rather than how you're doing it by using your constructor's initializer list. Something like: