函数类型的限定符.具有未指定的行为

Qualifier on function type .. has unspecified behavior

本文关键字:未指定 类型 函数      更新时间:2023-10-16
#ifndef SHAPEFACTORY_H_
#define SHAPEFACTORY_H_
#include <istream>
#include <map>
#include <string>
#include "shape.h"
typedef Shape *(createShapeFunction)(void);
/* thrown when a shape cannot be read from a stream */
class WrongFormatException { };
class ShapeFactory {
public:
    static void registerFunction(const std::string &string, const createShapeFunction *shapeFunction);
    static Shape *createShape(const std::string &string);
    static Shape *createShape(std::istream &ins);
private:
    std::map<std::string, createShapeFunction *> creationFunctions;
    ShapeFactory();
    static ShapeFactory *getShapeFactory();
};
#endif

这是头,我还没有实现任何方法,但我得到以下警告:

Qualifier on function type 'createShapeFunction' (aka 'Shape *()') has unspecified behavior

ps:这个标题是我的老师给的,作为作业,我必须实现方法

这是一个愚蠢的警告信息。它不是未指定的,但是您在registerFunction的第二个参数上添加的const限定将被忽略。

让我们看看createShapeFunctiontypedef:

typedef Shape *(createShapeFunction)(void);

你可以把这种类型读成"一个不接受参数并返回Shape*的函数"。那么你就有了这种类型的参数:

const createShapeFunction*

这是一个指向const函数类型的指针。没有const这样的函数类型,所以const被忽略,参数类型等同于createShapeFunction*。也就是指向上面定义的函数类型的指针。

有可能你的意思是createShapeFunction本身是一个函数指针类型:

typedef Shape *(*createShapeFunction)(void);

现在你可以把这种类型读成"指向函数的指针,不带参数,返回Shape*"。这将使参数const createShapeFunction*成为指向const函数指针的指针。

发出警告是因为类型const createShapeFunction*试图创建一个const限定的函数类型(因为createShapeFunction被定义为返回Shape*且不接受参数的函数类型)。这是c++ 11标准对此必须说的(第8.5.3/6段):

在函数声明符中添加cv-qualifier-seq的效果与在函数声明符顶部添加cv-qualifier-seq的效果不同函数类型的。在后一种情况下,cv限定符将被忽略。[注:函数类型有Cv-qualifier-seq不是一个cv限定类型;没有cv限定的函数类型。-end note][示例:

]
typedef void F();
struct S {
    const F f; // OK: equivalent to: void f();
};

-end example]

因此,编译器会警告您,您的意思可能不是您实际写的,因为函数类型的const条件将被忽略。