关于引发异常(类实例)

时间:2020-01-28 16:11:51

标签: c++ exception

已经搜索了该网站(和其他一些网站),但没有找到答案,我很茫然。问题很简单:我正在编写一个从std :: exception派生的类,并且试图抛出该类的实例。但是编译器不会允许我。

对于标题,我从runtime_error中借用了几行:

class StdException : public std::exception
{
public:
    StdException () {}
    explicit StdException (const StdException&);
    explicit StdException (const std::string&);
    explicit StdException (const char*);
    ~StdException() override { if(what_ptr) delete[] what_ptr; }
    const char* what() const noexcept override;

    StdException& operator= (const StdException&);

private:
    char* what_ptr;
};

.cpp文件中的代码也不多:

[snip]
StdException::StdException (const std::string& what_arg)
{
    size_t l = what_arg.size();
    what_ptr = new char[l+1];
    memset(what_ptr, '\0', l+1);
    strcpy(what_ptr, what_arg.c_str());
}
StdException::StdException (const char* what_arg)
{
    [the same in green]
}
[...]

当我试图扔这样的东西时,有趣的部分开始了:

[[noreturn]] void throw_something () {
    throw new StdException{"Foobar"};
}

只有使用此堆分配,编译器才会允许它通过。但这让我读了好几遍才明白,这是一个坏主意。没有,只是

    throw StdException{"Foobar"};

    StdException e{"Foobar"};
    throw e;

编译器发出没有匹配的构造函数... 的投诉。

正如我所说,我是C ++的新手。我的借口是为了平庸。


这是完整的代码:

“ include / execption.h”:

#ifndef EXCEPTION_H
#define EXCEPTION_H

#include <exception>
#include <string>
#include <cstring>

class StdException : public std::exception
{
public:
    StdException () {}
    explicit StdException (const StdException&);
    explicit StdException (const std::string&);
    explicit StdException (const char*);
    ~StdException() override { if(what_ptr) delete[] what_ptr; }
    const char* what() const noexcept override;

    StdException& operator= (const StdException&);

private:
    char* what_ptr;
};

exception.cpp:

#include "include/exception.h"

StdException::StdException (const StdException& e)
{
    size_t l = strlen(e.what_ptr);
    what_ptr = new char[l+1];
    memset(what_ptr, '\0', l+1);
    strcpy(what_ptr, e.what_ptr);
}

StdException::StdException (const std::string& what_arg)
{
    size_t l = what_arg.size();
    what_ptr = new char[l+1];
    memset(what_ptr, '\0', l+1);
    strcpy(what_ptr, what_arg.c_str());
}

StdException::StdException (const char* what_arg)
{
    size_t l = strlen(what_arg);
    what_ptr = new char[l+1];
    memset(what_ptr, '\0', l+1);
    strcpy(what_ptr, what_arg);
}

StdException& StdException::operator= (const StdException& e)
{
    size_t l = strlen(e.what_ptr);
    what_ptr = new char[l+1];
    memset(what_ptr, '\0', l+1);
    strcpy(what_ptr, e.what_ptr);
    return *this;
}

const char* StdException::what() const noexcept
{
    return what_ptr;
}

错误是:

没有匹配的构造函数来初始化'StdException' exception.h:11:5注意:候选构造函数不可行:需要0个参数,但提供了1个。

删除“空”构造函数无济于事。

0 个答案:

没有答案