关于operator new重载和异常的问题
为什么这个代码片段会输出很多“here”?
我认为程序应该在调用 throw std::invalid_argument( "fool" );
后终止。
#include <memory>
#include <iostream>
void* operator new(std::size_t size)
{
std::cout << "here" << std::endl;
throw std::invalid_argument( "fool" ); //commit out this, there would be many many ouputs
return std::malloc(size);
}
void operator delete(void* ptr)
{
return free(ptr);
}
int main()
{
//std::unique_ptr<int> point2int(new int(999));
int* rawpoint2int = new int(666);
}
Why this code snippet ouputs a lot of "here"?
I think the program should terminate when after throw std::invalid_argument( "fool" );
has been called.
#include <memory>
#include <iostream>
void* operator new(std::size_t size)
{
std::cout << "here" << std::endl;
throw std::invalid_argument( "fool" ); //commit out this, there would be many many ouputs
return std::malloc(size);
}
void operator delete(void* ptr)
{
return free(ptr);
}
int main()
{
//std::unique_ptr<int> point2int(new int(999));
int* rawpoint2int = new int(666);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std::invalid_argument
的 文档 包含线索:您可以看到字符串参数是按设计复制的。这意味着如果您以这种方式抛出此异常,则几乎可以保证重新输入
new
。您还应该注意,
malloc
可以返回nullptr
,这将违反operator new
的设计,该设计应返回有效指针或抛出异常。在这种情况下抛出的正常异常类型是 std::bad_alloc。我无法想象你为什么要抛出
std::invalid_argument
。我想您可能在某个构造函数中遇到了这个问题,并决定测试分配本身。从技术上讲,您可以通过传递默认构造的字符串作为参数来解决该问题:
Eww,yucky。我建议您找到一个更合适的异常来抛出(如果您确实需要一个异常),或者创建您自己的非分配异常。
The documentation for
std::invalid_argument
holds the clue:You can see that the string argument is copied by design. This means that re-entering
new
is pretty much guaranteed if you are throwing this exception in this way.You should also be aware that
malloc
can returnnullptr
which will violate the design ofoperator new
which should either return a valid pointer or throw.The normal kind of exception to throw in this case is
std::bad_alloc
. I cannot imagine why you are wanting to throwstd::invalid_argument
. I thought perhaps you were encountering this issue in a constructor somewhere and decided to test the allocation itself.Technically you can resolve the problem by passing a default-constructed string as the argument:
Eww, yucky. I recommend you find a more appropriate exception to throw (if you actually need one), or create your own non-allocating exception.