c++ - 对不完整类型的 std::vector 的引用或指针

标签 c++ templates c++11 vector

如此处回答: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/

相关文章:

c++ - cin 和 getline 跳过输入

c++ - 是否有一个 Visual Studio 插件可以防止编写不匹配的 { 和 }

c++ - 更改资源文件后如何在 CLion 中进行 CMake 构建

c++ - 解析来自 MS cl.exe 的编译器输出

c++ - 迭代器相等

c++ - 访问使用不同模板参数实例化的模板类的成员

c++ - 忽略注释 : offset of packed bit-field without using "-Wno-packed-bitfield-compat"

ios - 如何通过 XCode 模板添加 swift 编译器自定义标志

c++ - 在 dynamic_pointer_cast 之后调用派生类的构造函数

C++11 右值引用也调用复制构造函数