前向声明类的unique_ptr的C++11容器
C++11 container of unique_ptr of forward declared class
g++ -std=c++11
不编译包含容器的类,该容器包含指向前向声明类的唯一指针。问题:
- 为什么
- 有合理的变通办法吗
代码示例:
#include <vector>
#include <memory>
// variant 1 (with full class definition): compiles
class Bar { [..] };
using BarPtr = std::unique_ptr<Bar>;
// variant 2 (with shared instead of unique pointers): compiles
using BarPtr = std::shared_ptr<class Bar>;
// variant 0 (which is what we want): compilation fails below
using BarPtr = std::unique_ptr<class Bar>;
// end of variants
class Foo {
std::vector<BarPtr> vec;
public:
Foo() {} // compilation of variant 0 fails here:
// In instantiation of ‘void std::default_delete<Bar>::operator()(Bar*) const
// ...
// invalid application of ‘sizeof’ to incomplete type ‘Bar’
};
我已经看过如何转发声明要在unique_ptr和Is std::unique_ptr<的标准容器中使用的类;T>需要知道T?的完整定义?,但对于我的上述问题,没有找到令人信服的答案。
您需要将Foo的这些部分移动到实现文件中,该文件需要完整的Bar定义(请参阅Howard Hinnant的表:https://stackoverflow.com/a/6089065/2173029)。根据本指南,编制:
#include <vector>
#include <memory>
class Bar;
using BarPtr = std::unique_ptr<Bar>;
class Foo {
std::vector<BarPtr> vec;
public:
Foo(); // Needs Bar in implementation
~Foo();// Needs Bar in implementation
};
您可以这样做:
#include <vector>
#include <memory>
class Bar;
using BarPtr = std::unique_ptr<Bar>;
class Foo {
std::vector<BarPtr> vec;
public:
Foo() {} // variant 3 fails here:
// invalid application of ‘sizeof’ to incomplete type ‘Bar’
};
//Implementation goes here
class Bar{};
int main(){
Foo a;
}
实时演示
问题是不能通过指向不完整(正向声明)类型的指针进行删除。确保Bar
的定义在包含类的析构函数中可见,或者为看到它的unique_ptr
使用自定义deleter。另请参阅具有不完整类型won';t编译
行的错误消息
Foo() {};
似乎表明需要一个析构函数~Bar()
。但为什么呢?我的这部分问题仍然悬而未决。
然而,对于实际的解决方案,答案很简单:用替换上面的行
Foo();
并且在看到类CCD_ 6的完整定义的编译单元中实现CCD_。
相关文章:
- MSVC是否支持C++11样式的属性而不是__declspec
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 如何将模板转换为C++11之前的模板
- CLANG 编译器 说:变量"PTR"可能未初始化
- c++11评估顺序(未定义的行为)
- C++中的VLA,扩展名为std=C++11
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- "类模板示例<int>;"语句对 C++11 是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 如何使用lock_guard在c++11中实现scoped_lock功能
- C++11 中不同类型的对象的 std::array 的替代方案
- 为什么 -mmacosx-version-min=10.10 不阻止使用标记为从 10.11 开始的函数?
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- C++11共享Ptr,共享相同的参考计数器