I know that the keyword explicit
is used to prevent implict conversions of a passed argument to match the parameter list. I learned that one should always write the explicit
keyword in a constructor with only one argument but does that apply to the copy constructor too? Am I introducing any problems to my code if I write it that way?
Asked
Active
Viewed 165 times
2

simonides
- 3,040
- 3
- 19
- 34
-
2Sure Class f() { return Class(); } - explicit is bad here – Nov 24 '14 at 19:40
-
1`Foo copy_foo = foo;` will also fail – vsoftco Nov 24 '14 at 19:46
-
"I learned that one should always write the explicit keyword in a constructor with only one argument" -- You learned wrong. You only need to do that when you want to prevent the constructor from being used implicitly. That's why the keyword is called `explicit`. – Nov 24 '14 at 19:49
-
1@hvd the rule comes from a desire to prevent accidental type conversions. If you don't prefer to make constructors explicit it can lead to surprising bugs. – Mark Ransom Nov 24 '14 at 19:59
-
As I already said, I am aware of what the explicit does. The question should possibly better be: Are there any downsides of makeing the copy constructor explicit. Does it give me a hard time writing operator += in a string class or anything like that? @vsoftco I already stumbled about this and that's not what I was asking. – simonides Nov 24 '14 at 20:25
-
@MarkRansom Yes, that matches what I said. Type conversions are implicit uses of the constructor. If you don't want the constructor to be used implicitly, make it `explicit`. If you do want a constructor to be used implicitly, don't make it `explicit`. A hard rule to always make all constructors `explicit` that have one argument, without thinking about whether `explicit` makes sense for that constructor, makes no sense as a rule. – Nov 24 '14 at 21:21
-
@fridolin69 The answer in that question shows downsides of making the copy constructor explicit, in similar spirit as earlier comments on this question: what would otherwise be perfectly normal usage is suddenly prohibited. – Nov 24 '14 at 21:23