Skip to content

[Proposal] Error.what() rvalue move return #504

@BestITUserEUW

Description

@BestITUserEUW

Motivation:

I have a custom error class which currently has to copy Error::what_ which can get expensive with large error messages.

Possible Solution:

std::string what() && { return std::move(what_); }

Example:

class Error {
public:
    Error(const std::string& _what)
        : what_(_what) {}

    Error(const Error& e) = default;

    Error& operator=(const Error&) = default;

    /// Returns the error message, equivalent to .what() in std::exception.
    const std::string& what() const { return what_; }
    
    /// Only qualifies if Error is a rvalue reference
    std::string what() && { return std::move(what_); }

private:
    /// Documents what went wrong
    std::string what_;
};

struct MyLibError {
    std::string message;
    //....
};

auto ParseSomething() -> MyLibError {
    auto result = Error("Parsing failed");  // rfl error message can become really long if many fields are missing
                                            // making a copy expensive

    return MyLibError(std::move(result).what());  // Moved instead of expensive copy
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions