c++ - 为什么 MSVC 不能正确解析 this->sth 对重载 operator-> 的调用

标签 c++ visual-c++ operator-overloading clang language-lawyer

考虑以下代码:

#include <iostream>

class LayoutConstraintInfo {
public:
  void print() const {
    std::cout << "Called LayoutConstraintInfo::Print";
  }
};

class LayoutConstraint {
  LayoutConstraintInfo *Ptr;
  LayoutConstraintInfo *operator->() const { return Ptr; }

public:
  void print() const {
    std::cout << "Called LayoutConstraint::Print";
    this->print();
  }
};

int main() {
  LayoutConstraint().print();
  return 0;
}

程序因堆栈溢出异常而崩溃(使用 MSVC 19.00.24215.1)。

但是,看一下这个示例,我希望得到以下输出:

CalledLayoutConstraint::Print

CalledLayoutConstraintInfo::Print

这是因为我希望调用 this->print() 来调用重载的 LayoutConstraintInfo *operator->() 运算符。 因此,对 LayoutConstraint::Print 的调用将调用 LayoutConstraintInfo::Print

我发现这是将 Clang 项目移植到 MSVC:MSVC 发出递归警告导致运行时堆栈溢出。 Clang 似乎没有提示,但我的 Windows PC 上没有任何版本的 Clang

最佳答案

I expect a call to this->print() to call the overloaded LayoutConstraintInfo *operator->() operator.

没有。请注意,operator-> 仅使用类本身类型的对象调用,而不是类的指针。这意味着 LayoutConstraint::operator->() 将在使用 LayoutConstraint 调用时使用,而不是 LayoutConstraint *(例如 this )。 this->print() 总是会直接调用成员函数LayoutConstraint::print(),从而导致无限递归。

您可以将其更改为与 LayoutConstraint 类型的对象一起使用,例如 *this

void print() const {
  std::cout << "Called LayoutConstraint::Print";
  (*this)->print();
}

顺便说一句:你可以用 clang 试试 here .

关于c++ - 为什么 MSVC 不能正确解析 this->sth 对重载 operator-> 的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41650348/

相关文章:

c++ - C++ Cmake的OpenCV

c++ - 常量全局变量模板

c++ - 关于数据丢失的警告 c++/c

.net - VC++ 代码 DOM 可以从 VS 插件访问吗?

c++ - 一个简单的 boost.spirit 示例中的 error_invalid_expression 编译错误

java - 有没有办法在 Java 中向 GregorianCalendar 添加方法?

c++ - 运算符重载和 const_cast 的使用

c++ - 我如何比较单个 SET 中结构的两个属性?

c++ - 如何在 QtCreator (Linux Ubuntu) 中编译和运行一个随机的单个 C++ 文件?

c++ - wxTreeCtrl 上的 wxWidgets AddRoot() 无法添加超过一个节点