Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put extra-statements in list-initialization?

Tags:

c++

c++11

Given I have a class with a constructor which looks as follows:

MClass(const char *t_source);

In fact there are a lot of places where t_source is obtained from a file, so I'm considering making another constructor which takes FILE pointer instead and put most of the boilerplate inside of it. At the same time existing constructor also has a lot of use by itself and contains logic which i don't want to repeat more than once in the code. I was thinking about delegating constructor but can't see any way how i can leverage this feature as i need more than one statement to extract data from a FILE instance (like allocating a char array and reading from the FILE and deleting afterward). So essentially I want to do something like this:

MClass(FILE *t_file) : MClass(MNameSpace::readFile(t_file)) {}

But with some preliminary and post-call actions. Any idea?

like image 359
The Dreams Wind Avatar asked Jun 02 '26 00:06

The Dreams Wind


1 Answers

I find your case to be better solved by the named constructor idiom. Rather than trying to pigeonhole complexity into the limited space provided by the constructor context, I would simply add a new named function.

class MClass {
  // ...
public:
  static MClass fromFile(FILE *t_file);
};

MClass MClass::fromFile(FILE *t_file) {
  // Preparation
  MClass retVal(...);
  // Post actions
  return retVal;
}

Simple, easy to understand, and does what you want. It also conveys meaning very well when one sees

MClass obj = MClass::fromFile(...);

To boot, the named return value optimization (standardized) will avoid any extra copies from using a named function. The net result will be a single constructor invocation to initialize obj directly.

like image 107
StoryTeller - Unslander Monica Avatar answered Jun 05 '26 01:06

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!