2021年4月7日星期三

C++ Initialization by making a copy or using reference depending on the condition

І have a bool variable named do_copy.

If do_copy == true, I want to work with a copy, like
some_type model = input_model

If do_copy == false, I want to work with a reference, like
some_type& model = input_model

Code that does what I want:

some_type copy_model;  if (do_copy)      copy_model = input_model;  some_type& model = do_copy ? copy_model : input_model;  

It does not look very good, and I call the default constructor, which isn't necessary for do_copy == false.

Is there a way to make it more elegant?

https://stackoverflow.com/questions/66994832/c-initialization-by-making-a-copy-or-using-reference-depending-on-the-conditio April 08, 2021 at 06:15AM

没有评论:

发表评论