A class that supports taking ownership and not

I'm writing a Parser class. It takes 1 argument in its constructor which is a Lexer object.

The question is i dont know whether i should take it as a reference (leaving ownership with the user / caller) or not (taking ownership). It could be that the user would want to keep the lexer object alive for longer than the parser, but when not then it seems annoying to have to.

So i figured why not support both? It seems convenient that the user of the class can choose to instantiate a Parser with just a reference to a lexer, giving them control of when the lexer gets cleaned up, OR whether to pass on ownership to the Parser and then not have to worry about keeping the lexer object alive and cleaning it up when the parser is done with it.

The problem is im not entirely sure how this looks like. Should i have two constructors like this?
1
2
Parser::Parser(Lexer&)
Parser::Parser(Lexer&&)


or should it look like this?
1
2
Parser::Parser(std::unique_ptr<Lexer>)
Parser::Parser<std::shared_ptr<Lexer>)


i want to support both value semantics and pointer semantics

and how would you hook it all up with the member variables behind the scene?
also what are your throughts about this? is it silly? I think its convenient but i haven't ever seen anyone else do something like this
Last edited on
Does the parser change the Lexer object? If not, then consider passing as a const ref. If it does change then do you want the changes passed back to caller (pass by ref) or not (pass by value).

If you also want to support pointer (why?) then just pass a raw pointer - or const raw pointer if the contents pointed to don't change).
doing it both ways will make the code that uses the tool a bit harder to read/follow and debug for others if it ends up in a larger program. Then you have a this way over here, that way over there problem... and when just cruising through a lot of lines trying to spot a problem, its just annoying to have to stop to look up why its that way. At the same time yes, adaptable behavior does make it more powerful. Find your balance between when its worth it and when it just adds to confusion later on once its no longer fresh in your mind or someone else is looking.
Registered users can post here. Sign in or register to post.