[LLVMdev] object construction patterns and unique_ptr
Chris Lattner
clattner at apple.com
Sat Jun 16 15:51:39 PDT 2012
On Jun 15, 2012, at 3:48 PM, Nick Kledzik wrote:
> In lld we have a Reader class which is a factory that takes .o file(s) and produces an in memory lld::File object(s). But in doing so, there could be I/O errors (file not readable) or file may be malformed. We are also using C++11 in lld, so we use std::unique_ptr for managing object ownership.
>
> The Reader class currently has an interface that can be simplified down to:
>
> virtual error_code readFile(StringRef path, std::unique_ptr<lld::File> &result);
>
> But this interface has become awkward to use. There are two "return" values. This method is a unique_ptr "source" but the use of a by-refernce parameter means you have to start with an uninitialized unique_ptr and the readFile() has to std::move() into it. unique_ptr is much nicer to use as a return value.
Not a c++'11 expert here, but does a returning an std::tuple work?
> An other issue is that since llvm::error_code was designed to return a fixed set of strings, there is no way to return a dynamic error message (e.g. "relocation 27 is invalid").
I'm pretty sure that the linker can specify a custom error_category with whatever information you want, and then return an error_code put with that. Michael would know for sure, but it is definitely in the design of error_code for it to be extensible.
> In asking around for clean models on how to do this better, I've heard two interesting ideas:
>
> 1) Incorporate the error_code and string message into the File class. That is the factory method always returns a File object. But there is a method on File objects to query if they are valid or not. If they are not, there is a method to get the error_code and/or error string.
>
> 2) A variation on this is to have a new subclass of File called FileError. If the Reader cannot construct a real FileFoo object because of some error, it instead constructs a FileError object and returns that. The FileError object has methods to get the error_code and/or error string.
>
> With both these ideas the Reader method is:
>
> virtual std::unique_ptr<lld::File> readFile(StringRef path);
>
> which is much easier to use.
>
>
> Any recommendations on a good way to design this?
Would an API like:
virtual std::unique_ptr<lld::File> readFile(StringRef path, error_code &ErrorInfo);
make more sense?
-Chris
More information about the llvm-dev
mailing list