下面给出了代码的概要来演示问题,感谢您的时间。
在
RowOfData rowData = tableData[row];
,RowOfData
将调用复制构造函数并执行浅拷贝。在
tableData[row][col] = item;
,QtParameter
tableData[row][col]
将调用复制构造函数分配操作,然后调用QList<T>::node_copy
所以新条目tableData[row][col]
将被分配。问题: 为什么
tableData[row][col]
会调用QtParameter
复制构造函数?顺便说一下,
QtParameter
tableData[row][col]
不会调用复制构造函数什么时候rowData
在函数结束时被破坏。
类:
QtParameter::QtParameter( const QtParameter& rhs) :QVariant(rhs){}
class RowOfData : QList<QtParameter>
{
public:
RowOfData(const RowOfData& rhs);
private:
}
class TableData
{
public :
TableData();
virtual ~TableData();
bool setItem(int row, int col, QtParameter item);
protected:
QStringList columnHeader;
QStringList rowHeader;
QStringList rowFooter;
QList< RowOfData > tableData;
}
成员函数:
bool TableData::setItem(int row, int col, QtParameter item)
{
if(row<rowCount())
{
RowOfData rowData = tableData[row];
/*useless here and impact the tableData[row][col] copy constructer× */
if( col < tableData.at(row).size() )
{
tableData[row][col] = item;
}
}
}
template <typename T>
Q_INLINE_TEMPLATE void QList<T>::node_copy(Node *from, Node *to, Node *src)
{
Node *current = from;
if (QTypeInfo<T>::isLarge || QTypeInfo<T>::isStatic) {
QT_TRY {
while(current != to) {
current->v = new T(*reinterpret_cast<T*>(src->v));
++current;
++src;
}
} QT_CATCH(...) {
while (current-- != from)
delete reinterpret_cast<T*>(current->v);
QT_RETHROW;
}
...
}
最佳答案
一种可能是当成员函数TableData::setItem
由 QtParameter
类型的对象调用,因为该函数不是通过引用获取它,而是一个 QtParameter
类型的对象必须通过从前一个复制构造在函数内部创建!
如果你想避免这种情况,请引用它(最好是 const one):
bool TableData::setItem(int row, int col, const QtParameter& item)
继续前进,在函数内部:
RowOfData rowData = tableData[row];
有很小的可能性,如果这些不是最低级别的某种类型的迭代器/指针,那么这也可能是源。
最后在:
tableData[row][col] = item;
根据您提到的,另一种可能性可能是为 tableData[row][col]
的类定义赋值运算符本身的方式。 .
请记住,赋值运算符也是一个函数,如果它没有像这样声明:
assigned_to & operator=(const assigned_from &)
例如:
assigned_to & operator=(assigned_from)
与第一种情况相同,assigned_from 的对象将在赋值运算符内复制构造。
很多信息都没有给出,如果你指的是“深层复制”QList<T>::node_copy
,复制构造函数也可以发生在里面:
current->v = new T(*reinterpret_cast<T*>(src->v));
这是对 复制构造函数的明确调用。但是由于没有给出有关类型的信息,我不能肯定地说,这就是调用 复制构造函数的地方。
此外,除非您提供有关 QList<QtParameter>
的一些信息,关于为什么在 rowData
时没有发生“深层复制”,我无话可说。被破坏了。
关于c++ - 关于QList类型实例的复制构造函数的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160111/