如此处回答:How can an incomplete type be used as a template parameter to vector here?在实例化模板组件时使用不完整类型作为模板参数可能会导致未定义的行为。但是,当我们只有指向不完整类型的模板组件的指针/引用作为参数时,该规则是否成立?在这种情况下是否也会发生实例化?
例如:
// SomeAlgoInterface.hpp
#include <vector>
struct Result; // forward declaration
class SomeAlgoInterface
{
public:
virtual ~SomeAlgoInterface() = default;
public:
// the following line is definitely OK, ...
virtual void f1(const Result & result) = 0;
// ... but I'm not quite sure about the following one
virtual void f2(const std::vector<Result> & results) = 0;
};
换句话说,上面的代码是否有效?
最佳答案
声明是正确的,只要您不调用 f2
。
如果你不调用f2
,编译器不需要知道Result
类的内部。声明中没有存储分配。
如果某个编译单元调用f2
,你需要为Result
类提供完整的类型,或者你需要另一个引用参数来调用f2
:
void another_f(SomeAlgoInterface& i, std::vector<Result>& results)
{
i.f2(results);
}
关于c++ - 对不完整类型的 std::vector 的引用或指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34189482/