所以 ~T() 甚至适用于标准类型(不是类/结构)我假设 operator=(const T &)
也可以作为默认方法有效,但不是:
#include <new>
template <class T> void foo(T el) {
alignas(T) unsigned char buf[sizeof(T)];
T *ptr = new (buf) T(el);
// error: request for member 'operator=' in '* ptr', which is of non-class type 'int'
// ptr->operator=(42);
ptr->~T();
}
int main() { foo(42); }
~T() 合成结构是否与标准类型兼容?
最佳答案
是的。该标准定义了“伪析构函数调用”,例如 ptr->~T()
或 ref.~T()
对内置标量类型有效 (§[expr.prim.id.dtor]):
- An id-expression that denotes the destructor of a type
T
names the destructor ofT
ifT
is a class type (11.4.6), otherwise the id-expression is said to name a pseudo-destructor.- If the id-expression names a pseudo-destructor,
T
shall be a scalar type and the id-expression shall appear as the right operand of a class member access (7.6.1.4) that forms the postfix-expression of a function call (7.6.1.2). [Note: Such a call has no effect. —end note]
无论好坏,对于其他对内置标量类型有效的运算符都没有做同样的事情,因此(如您所见)您不能引用
some_int.operator=
, 例如)。已经(相当多的)讨论了某种统一的函数调用语法,这将允许编译器至少整理出一些这样的东西,但尽管它至少被提出过几次(早期由 Francis Glassborrow 提出,更多最近由 Bjarne 和 Herb Sutter),它没有被接受。如果您对此感兴趣,除了在 C++ 中使用它之外,D 确实支持此顺序的某些内容,您可能会觉得研究很有趣。
除此之外,虽然它并不像您希望的那么容易,但您可以使用 SFINAE 在
foo = bar;
之间进行选择。和 foo.operator=(bar);
,如果您真的需要这样做(尽管我承认,我不确定您从 .operator=
语法中获得了什么优势)。
关于c++ - 为什么 operator= 不适用于具有新模板放置的标准类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67973135/