我最近开始为自己调查Qt并提出以下问题:
假设我有一些QTreeWidget* widget.在某些时刻,我想添加一些项目,这是通过以下调用完成的:
QList<QTreeWidgetItem*> items;
// Prepare the items
QTreeWidgetItem* item1 = new QTreeWidgetItem(...);
QTreeWidgetItem* item2 = new QTreeWidgetItem(...);
items.append(item1);
items.append(item2);
widget->addTopLevelItems(items);
Run Code Online (Sandbox Code Playgroud)
到目前为止它看起来还不错,但我实际上并不了解谁应该控制对象的生命周期.我应该用一个例子解释一下:
让我们说,另一个函数调用widget->clear();.我不知道这个调用下面会发生什么,但我确实认为,内存分配item1和item2没有得到安置在这里,因为他们的OWNAGE实际上并没有转移.而且,砰的一声,我们有内存泄漏.
问题如下 - 确实Qt可以为这种情况提供一些东西吗?我可以使用boost::shared_ptr或任何其他智能指针,并写出类似的东西
shared_ptr<QTreeWidgetItem> ptr(new QTreeWidgetItem(...));
items.append(ptr.get());
Run Code Online (Sandbox Code Playgroud)
但我不知道Qt本身是否会尝试delete对我的指针进行显式调用(因为我将它们声明为shared_ptr管理状态,这将是灾难性的).
你会如何解决这个问题?也许一切都很明显,我想念一些非常简单的东西?
我正在编写C++代码,我想用其扩展名打印当前文件名.是的,这是常见问题之一.一种解决方案是使用argv [0].这很酷,但它没有给出扩展名.我可以用扩展名吗?
这个问题已经在命名空间内的未命名命名空间链接中讨论过 ,但对于如何访问嵌套在命名空间下的未命名命名空间的变量(如果两个变量相同)没有提供完美的答案
考虑这段代码
namespace apple {
namespace {
int a=10;
int b=10;
}
int a=20;
}
int main()
{
cout<<apple::b; //prints 10
cout<<apple::a; // prints 20
}
Run Code Online (Sandbox Code Playgroud)
未命名的命名空间"variable a"始终是隐藏的。如何访问"variable a"未命名的命名空间?
在命名空间内声明未命名的命名空间是否合法?
所以我一直在寻找动态数组的实际工作方式.我发现的是两个不同的概念.
在C++中
在C++中,动态数组通常由向量实现.向量将容量设置为0,增加计数以插入新元素,然后将新插入的容量大小加倍.
vector.h
/*
* Implementation notes: Vector constructor and destructor
* -------------------------------------------------------
* The constructor allocates storage for the dynamic array and initializes
* the other fields of the object. The destructor frees the memory used
* for the array.
*/
template <typename ValueType>
Vector<ValueType>::Vector() {
count = capacity = 0;
elements = NULL;
}
Run Code Online (Sandbox Code Playgroud)
用于扩展矢量大小
/*
* Implementation notes: expandCapacity
* ------------------------------------
* This function doubles the array capacity, copies the old elements into
* the new …Run Code Online (Sandbox Code Playgroud) c++ ×4
arrays ×1
c++14 ×1
file ×1
java ×1
memory ×1
memory-leaks ×1
namespaces ×1
qt ×1
shared-ptr ×1
stdvector ×1