C++中默认构造的对象return和空大括号return有什么区别?
What is the difference between default constructed object return and empty braces return in C++?
在下面的代码中:
#include <memory>
struct A;
std::unique_ptr<A> ok() { return {}; }
std::unique_ptr<A> error() { return std::unique_ptr<A>{}; }
Clang++ 编译良好的 ok()
函数并拒绝 error()
函数并显示消息:
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,
演示:https://gcc.godbolt.org/z/M8qofYbzn
C++ 中的默认构造对象 return 和空大括号 return 之间是否存在任何真正的区别(一般而言,在这种特殊情况下)?
都不应该编译。
结果对象的析构函数is always potentially invoked。在 unique_ptr
的情况下,需要 A
才能完成。
在下面的代码中:
#include <memory>
struct A;
std::unique_ptr<A> ok() { return {}; }
std::unique_ptr<A> error() { return std::unique_ptr<A>{}; }
Clang++ 编译良好的 ok()
函数并拒绝 error()
函数并显示消息:
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,
演示:https://gcc.godbolt.org/z/M8qofYbzn
C++ 中的默认构造对象 return 和空大括号 return 之间是否存在任何真正的区别(一般而言,在这种特殊情况下)?
都不应该编译。
结果对象的析构函数is always potentially invoked。在 unique_ptr
的情况下,需要 A
才能完成。