c++ - 为什么 operator= 不适用于具有新模板放置的标准类型?

标签 c++ syntax operator-overloading

所以 ~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]):

  1. 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.
  2. 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/

相关文章:

c++ - 为什么解引用运算符 (*) 也用于声明指针?

scala - 元组的多重赋值是否比多重赋值语句慢?

ruby - 使用几种同样抽象的语法变体来编码某些东西有什么值(value)?

c++ - 如何在 C++ 中重载非交换运算符的两种可能性?

c++ - 部分模板特化的下标运算符重载

c++ - 从内存加载 png 时 libpng 错误无效 block 类型

c++ - 使用 MinGW 编译的 libx264 - 缺少 __umoddi3、__udivdi3、_fseeko64 和 __chkstk_ms

c# - 是否有在 C# 中重载赋值运算符的解决方法?

c++ - C4800 : 'float' : forcing value to bool 'true' or 'false' (performance warning)

c++ - MS 色带 : draw button icon from code