[英]how to assign a shared pointer of type structure to a shared pointer of class type
在下面的函数中, info
是一个包含getHDDList
函数的类,而HDDList
是一个结构体。 但是当我将getHDDList
的输出分配给 hdd 时,它说no operator "=" matches this operands
:
HDDList* smc_getHDDList(Authorization* autho)
{
HDDList retVal;
//HDDList* hdd = new HDDList;
std::shared_ptr<info> inf (new info(autho));
std::shared_ptr<HDDList> hdd ;
try
{
//inf.get()->getHDDList();
//hdd = inf.get()->getHDDList();
}
catch (const std::invalid_argument& e)
{
THROW_EXCEPTION
}
return hdd;
}
这是我的HDDList
结构:
struct HDDList
{
const char* name;
double totalSize;
double freeSize;
double usedSize;
};
这是getHDDList
函数:
HDDList* info::getHDDList()
{
int num;
num = std::stoi(numberOfHDDs());
HDDList* list = new HDDList[num];
for (int i = 0; i < num; i++)
{
list[i].name = listOfHDDs(i);
}
return list;
}
我使用了共享指针,因为当我在返回之前使用原始指针和删除指针时,我在接收结构时遇到问题(它没有返回结构的第一个成员)。
如何将getHDDList
的输出分配给hdd
?
可能可以尝试类似的东西:
hdd.reset(inf->getHDDList());
如果您采用此路线,则需要更新返回类型。
这段代码有几个问题,所以让我看看我们是否能做到这一点。
首先,在您的结构 HDDList 中,您有一个 const 指针名称; 这指向哪里?
我认为如果你将它声明为std::string
以便在节点被销毁时它是自包含的,你会更好。
struct HDDList
{
std::string name;
double totalSize;
double freeSize;
double usedSize;
};
否则,如果名称指向某个分配的字符串,您将需要处理该字符串以及 HHDList 或 unique_ptr 的自定义删除器中的析构函数。
您想在函数 getHDDList() 中创建一个 HDDList 数组
HDDList* info::getHDDList() {...}
请注意,您没有返回数组的大小。 所以调用者无法知道数组有多长,因为它只是得到一个指向数组开始位置的指针。
(如果您的数据中没有未提及的秘密标记)。
因此,让我们添加大小并返回一个包含在 unique_ptr 中的数组:
std::unique_ptr<HDDList[]> info::getHDDList(int& num)
{
num = std::stoi(numberOfHDDs());
auto list = std::make_unique<HDDList[]>(num);
for (int i = 0; i < num; ++i)
{
list[i].name = listOfHDDs(i);
}
return list;
}
在您的调用者函数中,您现在拥有数组大小加上包含在智能指针中的数组的信息:
HDDList* smc_getHDDList(Authorization* autho)
{
auto inf = std::make_unique<info>(autho);
std::unique_ptr<HDDList[]> hdd;
try
{
int hddSize{0};
hdd = inf->getHDDList(hddSize);
...
}
catch (const std::invalid_argument& e)
{
// write out exception
// rethrow if you want
}
return hdd;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.