我已经将“调用隐式删除的复制构造函数”编译错误的问题隔离到在声明类成员时使用 ostringstream 类型。在下面的示例中,定义了示例的 Reading 类的对象的 STL 列表。在调用 push_back 时,编译器搜索复制构造函数,但编译失败,似乎是因为 Readings 的复制构造函数已被隐式删除。
当我注释掉引用payloadString的两行时,程序编译。
我在想我的问题可能是 ostringstream 是引用类型,如下所述:
https://en.cppreference.com/w/cpp/language/copy_constructor “T 有一个右值引用类型的数据成员;” 被引用为隐式删除复制构造函数的可能原因之一。
Q的。谁能确认我上述关于 ostringstream 是导致问题的引用类型的假设是否正确?
我使用 ostringstream 的原因在这个人为的例子中并不明显。也许我需要找到另一种方法来处理这个字符串,但是任何人都可以建议一种可以在这里工作的方法吗?
// testing a problem where ostringstream causes implicitly deleted copy constructor
//
// using ostringstream in a class definition seems to cause implicit deletion of the copy constructor
#include <iostream>
#include <sstream>
#include <list>
#include <string>
using namespace std;
class Reading {
public:
double elevation;
std::ostringstream payloadString; // using ostringstream here causes implicit deletion of the copy constructor
double speed;
// constructors and member functions
Reading(); // initialisation constructor declaration
private:
};
Reading::Reading(): // initialisation constructor definition
elevation(0.0),
payloadString("_null_null_"), // commenting out this line and the previous definition in the class makes the problem go away
speed(0.0)
{}
int main()
{
std::list<Reading> readingsList; // a list of readings
Reading fakeReading; // just initialises with dummy data
// this line is what causes the compiler to complain about implicitly deleted copy constructors
readingsList.push_back(fakeReading);
return 0;
}