我试图创建一个在向量中的项目之间共享的类型的单个实例。每个向量的项类型都需要在构造函数中传递引用参数,但我似乎无法让向量正确初始化。
//The type of each item in the vector
class PollingConfig_t
{
public:
PollingConfig_t(DebugPrinter_t& _debugPrinter) : _debugPrinter(debugPrinter) {}
private:
DebugPrinter_t& _debugPrinter; //Reference to the global instance of DebugPrinter_t
}
对于实际的全局变量:
DebugPrinter_t DebugPrinter(true); //One instance shared among vector items
std::vector<PollingConfig_t> PollingConfigs(4, PollingConfig_t(DebugPrinter)); //4 instances of PollingConfig_t, each with reference to DebugPrinter.
这不会编译并给我一个错误:
error: use of deleted function 'PollingConfig_t& PollingConfig_t::operator=(const PollingConfig_t&)'
但是,如果我简单地删除 _debugPrinter 声明中的&符号,我就可以让它按预期工作。
private:
DebugPrinter_t _debugPrinter;
但这不会为向量的每个项目创建原始实例
DebugPrinter
的副本吗?我的意思是,如果 _debugPrinter
被声明为 DebugPrinter_t
而不是 DebugPrinter_t&
,它就不再是引用了,对吗?
正如 Remy Lebeau 在评论中指出的那样,您提出的代码确实可以编译,并且可以通过这种方式初始化向量。
您使用矢量时的其他原因导致了错误。编译器表示您需要提供一个复制赋值运算符,因为编译器无法为引用成员合成一个复制赋值运算符。您无法重新定位引用,这使得它变得很困难,因此如果您确实需要进行分配,您可能需要使用指针。