为什么 operator= 不适用于带有新模板放置的标准类型?
Why operator= is not working for standard types with template placement new?
所以 ~T() 甚至对标准类型(不是 classes/structs)也有效 我假设 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 of T
if T
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 select 在 foo = bar;
和 foo.operator=(bar);
,如果你真的需要这样做(虽然我承认,我不确定你从 .operator=
语法中获得什么优势)。
所以 ~T() 甚至对标准类型(不是 classes/structs)也有效 我假设 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 select 在 foo = bar;
和 foo.operator=(bar);
,如果你真的需要这样做(虽然我承认,我不确定你从 .operator=
语法中获得什么优势)。