【发布时间】:2017-11-14 19:38:23
【问题描述】:
我已决定转向现代 c++ 实践,并尝试调整我的旧代码以使用智能指针。我有一个包含数据包数据的数据包类,以及其他一些变量。
class Packet
{
public:
Packet(int connId, std::shared_ptr<char[]> buff, size_t pLen)
: connID(connId), packetLen(pLen)
{
buffer = buff;
}
Packet(){}
int connID;
size_t packetLen;
std::shared_ptr<char[]> buffer;
};
我有一个测试函数,可以创建数据并将其插入新分配的缓冲区。
std::vector<Packet> packetV;
void createPacket()
{
std::shared_ptr<char[]> data = std::make_shared<char[]>(10);
for (int i = 0; i < 5; ++i)
{
uint8_t byte = 5;
memcpy(*data.get() + i, &byte, sizeof(uint8_t));
}
packetV.push_back(Packet(1, data, 5*sizeof(uint8_t)));
}
//(Main function)
void main()
{
std::string input;
do
{
std::cin >> input;
if (input == "packet") createPacket();
else if (input == "exit") input.clear();
else if (input == "empty") packetV.clear();
else if (input == "show") std::cout << packetV.size() << std::endl;
} while (input.size() > 0);
}
当我尝试编译代码时,出现以下错误:
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\type_traits(1192): error C2070: 'char []': illegal sizeof operand
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\type_traits(1199): note: see reference to class template instantiation 'std::aligned_union<1,_Ty>' being compiled
1> with
1> [
1> _Ty=char []
1> ]
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\memory(1731): note: see reference to alias template instantiation 'aligned_union_t<1,char[]>' being compiled
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\memory(1778): note: see reference to class template instantiation 'std::_Ref_count_obj<_Ty>' being compiled
1> with
1> [
1> _Ty=char []
1> ]
1>c:\users\...\documents\visual studio 2017\projects\..\...\source.cpp(29): note: see reference to function template instantiation 'std::shared_ptr<char []> std::make_shared<char[],int>(int &&)' being compiled
有人可以帮助我理解错误并建议我如何使用智能指针设计将数据插入和提取到 char * 数组中!?
【问题讨论】:
-
使用 std::vector 或 std::string!
-
s/
*data.get()/data.get() -
由于其他评论没有为
std::vector提供任何动机,我认为主要的批评是当您使用std::shared_ptr时,数据将如何共享并不明显。如果您确实想封装拥有数据,请使用std::unique_ptr或std::vector -
另外你应该注意使用
uint8_t可能是一个更适合用消息包来表示任意字节值的类型。 -
在转向现代 C++ 实践之前,您应该学习如何遵循旧的实践。例如数据封装和适当的成员初始化。
标签: c++ shared-ptr smart-pointers