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)?
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.