我有一个ostringstream对象,我正试图在其中插入一些字符,但是这个ostringstream对象在一个名为pOut的shared_ptr中。当我尝试取消对pOut的引用时,我总是得到一个访问冲突错误。
这是我正在尝试做的事情的一个简化版本:
#include <iostream>
#include <sstream>
int main()
{
std::shared_ptr<std::ostringstream> pOut;
*pOut << "Hello";
std::cout << pOut->str();
}在我看来,这应该是可行的,因为下面看到的程序编译和运行没有任何问题:
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream out;
out << "Hello";
std::cout << out.str();
}为什么取消引用对象会引发访问冲突错误,我该如何解决这个问题?下面是我得到的错误。
Exception thrown at 0x00A22112 in MemoryIssueTest.exe: 0xC0000005: Access violation reading location 0x00000000.
发布于 2020-09-26 23:12:08
您创建了pointer对象,但它最初设置为nullptr、NULL或0。因此,访问该内存肯定会导致分段错误或访问冲突。你需要给它一个值。因此,不是这样:
std::shared_ptr<std::ostringstream> pOut;使用以下命令:
std::shared_ptr<std::ostringstream> pOut = std::make_shared<std::ostringstream>();这应该可以解决您的问题。
https://stackoverflow.com/questions/64071701
复制相似问题