Zizheng Tai
Zizheng Tai

Reputation: 6616

Construction in return statement

Suppose we have a class Foo with a non-explicit constructor from an int. Then for the following functions:

Foo makeFoo1() { return 123; }
Foo makeFoo2() { return {123}; }

I think makeFoo1 requires that Foo's copy/move ctor is accessible, and it's possible (though unlikely) that the compiler does not elide the copy and thus results in a true copy/move.

For makeFoo2, since we are using copy-list-initialization, no copy/move can ever occurred.

Should I really worry about this and put arguments to non-explicit ctors in braces whenever I can (as in makeFoo2)? (Say if I'm a library author and expect the library to be used with subpar compilers for embedded system.)

Upvotes: 11

Views: 377

Answers (1)

einpoklum
einpoklum

Reputation: 131495

I'll go out on a limb here and combine a practical answer with a weak language-lawyery justification.

The weak language-lawyer argument: If I understand this cppreference.com description correctly, you are not guaranteed RVO when initializing with an initializer list (makeFoo2) any more than you are with just your int return (makeFoo1). So, don't surround your int in braces.

Practical argument 1: Come one, those braces have got to be redundant. They should be redundant. So don't use them, it doesn't seem right.

Practical argument 2: The principle of least surprise. Using those braces, you're implying there's something wrong with the brace-less form. I would be confused and slightly surprised by the braces (albeit not very confused).

Practical argument 3: In these kinds of situations - trust the compiler. This is not where your performance bottleneck is (and if it is - make it an inline function, and it won't be; or use a reference if you have an existing object; etc).

Upvotes: 3

Related Questions