Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between default constructed object return and empty braces return in C++?

In the following code:

#include <memory>

struct A;

std::unique_ptr<A> ok() { return {}; }

std::unique_ptr<A> error() { return std::unique_ptr<A>{}; }

Clang++ compiles fine ok() function and rejects error() function with the message:

In file included from /opt/compiler-explorer/gcc-11.1.0/lib/gcc/x86_64-linux-gnu/11.1.0/../../../../include/c++/11.1.0/memory:76:
/opt/compiler-explorer/gcc-11.1.0/lib/gcc/x86_64-linux-gnu/11.1.0/../../../../include/c++/11.1.0/bits/unique_ptr.h:83:16: error: invalid application of 'sizeof' to an incomplete type 'A'
        static_assert(sizeof(_Tp)>0,

Demo: https://gcc.godbolt.org/z/M8qofYbzn

If there any real difference between default constructed object return and empty braces return in C++ (both in general, and in this particular case)?

like image 433
Fedor Avatar asked Aug 06 '21 08:08

Fedor


People also ask

Where does the object C reside in the stack frame?

Also, notice the address of c. Even though the object c is instantiated inside the function f (), c resides in the stack frame of main ().

Why is there no return statement in void return type function?

Not using return statement in void return type function: When a function does not return anything, the void return type is used. So if there is a void return type in the function definition, then there will be no return statement inside that function (generally).

What are the limitations of return statement in C/C++?

Few are mentioned below: Methods not returning a value: In C/C++ one cannot skip the return statement, when the methods are of return type. The return statement can be skipped only for void types. Not using return statement in void return type function: When a function does not return anything, the void return type is used.

What are the arguments and parameters of return by reference?

and parameters are the passed arguments to it. Below is the code to illustrate the Return by reference: Since reference is nothing but an alias (synonym) of another variable, the address of a, b and x never changes.


Video Answer


1 Answers

Neither should compile.

The destructor for the result object is always potentially invoked. In the case of unique_ptr that requires A to be complete.

like image 136
Jeff Garrett Avatar answered Oct 19 '22 17:10

Jeff Garrett