我已经决定转向现代的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 *数组中并将其提取吗!?
发布于 2017-11-14 19:45:09
std::shared_ptr
不是专门用于当前标准C++版本中的数组的。预计C++20将提供支持。
与此同时,你有几个选择:
std::string
,它会自动管理动态大小的字符串,当有人说“在内存中保存一堆字符!”时,它确实应该是您的默认响应!std::unique_ptr<char[]>
。与shared_ptr
不同,unique_ptr
是专门用于数组的,这意味着您试图使用的构造将使用它。std::vector<uint8_t>
。就存储的数据而言,这(几乎)相当于std::string
,但在这里,用法更冗长:数据不仅仅是字符串,具体而言,它是原始二进制数据。https://stackoverflow.com/questions/47293928
复制相似问题