C++ Coding Style – Using Unnamed Object to Invoke Method

ccoding-stylerefactoring

If I have a class with only only public method. When I use this class, is it good to use unnamed object to invoke its method?

normal:

TaxFileParser tax_parser(tax_file_name);
auto content = tax_parser.get_content();

or unnamed object version:

auto content = TaxFileParser(tax_file_name).get_content();

Because I've told that we should avoid temporary as possible. If tax_parser object is used only once, can I call it a temporary and try to eliminate it?

Any suggestion will be helpful.

Best Answer

The temporary object is still created, whether you gave it a name or not. Your two lines are equivalent.

If there is only one public method, I'd ask why this is even a class. Can it be handled by being a function with tax_file_name as parameter? Then you would not have an otherwise useless temporary object.

class TaxFileParser
{
   public:
     static whatever_t get_content(const std::string& file)
     {
       return result_from_file_in_question();
     }
};

auto content = TaxFileParser::get_content(tax_file_name);
Related Topic