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)?
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 ().
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With