gpt4 book ai didi

c++ - 是否允许所有未使用的未定义方法?

转载 作者:可可西里 更新时间:2023-11-01 17:45:23 26 4
gpt4 key购买 nike

这是一个有未定义方法的类。似乎编译器允许构造此类的实例,只要从未调用未定义的成员函数即可:

struct A {
void foo();
};

int main() {
A a; // <-- Works in both VC2013 and g++
a.foo(); // <-- Error in both VC2013 and g++
}

这是一个类似的情况,但涉及到继承。子类 Bar 扩展了基类 FooFoo 定义了一个方法g()Bar 声明同名方法但未定义它:

#include <iostream>

struct Foo {
void g() { std::cout << "g\n"; }
};

struct Bar : Foo {
void g();
};

int main() {
Bar b; // Works in both VC2013 and g++
b.Foo::g(); // Works in both VC2013 and g++
b.g(); // Error in both VC2013 and g++
}

这是上面的变体。这里唯一的区别是 g()FooBar 都是虚拟的:

#include <iostream>

struct Foo {
virtual void g() { std::cout << "g\n"; }
};

struct Bar : Foo {
virtual void g();
};

int main() {
Bar b; // Works in g++. But not in VC2013, which gives
// 'fatal error LNK1120: 1 unresolved externals'

b.Foo::g(); // Works in g++, but VC2013 already failed on b's construction
b.g(); // Error in g++, but VC2013 already failed on b's construction
}

有关 VC2013 和 g++ 之间不同行为的对比,请参阅代码注释。

  1. 哪个编译器是正确的,如果有的话?
  2. 为什么 VC2013 的编译器在带有 virtual 关键字的版本和没有 virtual 关键字的版本中有一些不同的提示?
  3. 是否始终允许未使用的未定义方法?如果不是,他们在什么情况下不允许?
  4. Barg() 声明算作重写吗即使 Bar 没有提供定义?

最佳答案

Which compiler is correct, if any?

他们都是对的。您的代码错误,无需诊断。 [class.virtual]/11

A virtual function declared in a class shall be defined, or declaredpure (10.4) in that class, or both; but no diagnostic is required(3.2).

[intro.compliance]/2:

If a program contains a violation of a rule for which no diagnostic isrequired, this International Standard places no requirement onimplementations with respect to that program.

查看 GCC 的优化设置,它们可能会影响行为。


Are unused undefined methods always allowed?

当且仅当它被 odr 使用时,必须定义一个成员函数。 [basic.def.odr]/3:

Every program shall contain exactly one definition of every non-inlinefunction or variable that is odr-used in that program; no diagnosticrequired.

现在考虑 [basic.def.odr]/2:

An expression is potentially evaluated unless it is an unevaluated operand (Clause 5) or a subexpression thereof.
[…]
A virtual member function is odr-used if it is not pure.
A non-overloaded function whose name appears as a potentially-evaluated expression or a member of a set of candidate functions, if selected by overload resolution when referred to from a potentially-evaluated expression, is odr-used, unless it is a pure virtual function and its name is not explicitly qualified.

您仍然可以在 decltypesizeof 中使用未定义的非虚拟成员函数。但是非纯虚函数之所以被使用,仅仅是因为它们不是纯的。


Does Bar’s declaration of g() count as overriding even when Bardoesn't provide a definition?

是的。

关于c++ - 是否允许所有未使用的未定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26811356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com