为什么下面的代码编译,即使我有未定义的成员函数? [英] Why does the following code compile even though I have undefined member functions?

查看:152
本文介绍了为什么下面的代码编译,即使我有未定义的成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在中途工作这段代码,并认为这显然不会编译,然后点击构建按钮。我很惊讶,它不仅编译,但链接和工作以及。

I was halfway through working on this piece of code and thought this is obviously not going to compile before hitting the build button. I was surprised that it not only compiled, but linked and worked as well.

如果我想我会说SFINAE负责编译...是吗?

If I were to guess I would say that SFINAE is responsible for it compiling... is it?

struct BaseClass
{
public:
  BaseClass() {}

  template<typename T>
  BaseClass(const T& a_other)
  {
    int i = 0; // for break point
  }

  template<typename T>
  BaseClass& operator= (const T& a_other)
  {
    int i = 0; // for break point
    return *this;
  }

private:

  BaseClass(const BaseClass& a_other); // Does not have a definition
  BaseClass& operator= (const BaseClass& a_other); // Does not have a definition

};

struct MyClass : public BaseClass
{
};

int main()
{
  MyClass i, j;
  i = j;

  return 0;
}

EDIT :我使用Visual-C ++ 2008 ,也许是VS的奇怪怪癖

EDIT: I am using Visual-C++ 2008, maybe it is an odd quirk of VS

推荐答案

代码不合法​​。

i = j 调用 MyClass 中隐式定义的副本赋值运算符。此函数为其每个子对象调用复制赋值运算符,包括直接基类[class.copy 12.8 p28]。

i = j calls the implicitly defined copy assignment operator in MyClass. This function calls the copy assignment operator for each of its sub-objects, including direct base classes [class.copy 12.8 p28].

如果向复制赋值添加代码BaseClass的操作符你可以看到VS出错的地方:

If you add code to the copy assignment operator for BaseClass you can see where VS is going wrong:

  template<typename T>
  BaseClass& operator= (const T& a_other)
  {
    std::cout << typeid(T).name() << '\n';
    int i = 0; // for break point
    return *this;
  }

对我来说,打印出struct MyClass。 VS通过直接传递 MyClass:operator = 中接收到的参数来调用 BaseClass BaseClass j的子对象。

For me this prints out "struct MyClass". VS is calling the BaseClass copy assignment operator by passing the parameter received in MyClass:operator= directly, rather than just the BaseClass sub object of j.

SFINAE不起作用,因为模板函数不会失败。 VS正在简单地生成隐式复制赋值运算符。

SFINAE doesn't come into play because the template functions aren't failing. VS is simply generating the implicit copy assignment operator incorrectly.

总结:
VS正在生成隐式复制赋值运算符

To sum up: VS is generating the implicit copy assignment operator as

MyClass &operator=(const MyClass& rhs) {
    static_cast<BaseClass&>(*this).operator=(rhs);
    return *this;
}

应该是:

MyClass &operator=(const MyClass& rhs) {
    static_cast<BaseClass&>(*this).operator=(static_cast<const BaseClass&>(rhs));
    return *this;
}

这篇关于为什么下面的代码编译,即使我有未定义的成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆