简体   繁体   English

C ++抛出范围

[英]C++ throw scope

When switching compilers my old'n trusted throw code (example below) fails. 当切换编译器时,我的旧可信throw代码(下面的例子)失败了。 I'm guessing that it is the err variable scope that is the problem? 我猜这是问题的err变量范围? What happens is that when trying to access the string part of err it has been deallocated. 会发生什么事情,当试图访问err的字符串部分时,它已被释放。 What would be a better way of doing something like this using a custom exception class? 使用自定义异常类做一些更好的方法是什么?

if (someErrorHappend)
{
    std::stringstream err;
    err << "Some error #" << GetLastError() << ".";
    throw SomeCustomException("MyClass", "MyFunc", err.str().c_str());
}

c_str is a non-owning pointer, so you shouldn't pass it to the constructor that will retain it directly. c_str是一个非拥有指针,因此您不应将其传递给将直接保留它的构造函数。

To fix the problem, simply adjust the constructor SomeCustomException to accept a std::string instead of a char * . 要解决这个问题,只需调整构造函数SomeCustomException即可接受std::string而不是char * The char * will be converted to a string , which is an owning object. char *将转换为string ,该string是拥有对象。

In the future, you can migrate code by removing the c_str() call and leaving only err.str() . 将来,您可以通过删除c_str()调用并仅err.str()来迁移代码。 The compiler will apply C++11 move semantics to remove one copy operation. 编译器将应用C ++ 11移动语义来删除一个复制操作。

Don't worry about running out of memory. 不要担心内存不足。 The stringstream code is already allocating on the heap for its internal string, and there's no difference between that and the exception constructor — both run before the throw , and if you ran out of memory beforehand, you should already be in an exception handling state anyway. stringstream代码已经在堆上为其内部字符串分配,并且它和异常构造函数之间没有区别 - 两者都在throw之前运行,如果你事先没有内存,那么你应该已经处于异常处理状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM