【发布时间】:2025-12-16 05:30:01
【问题描述】:
如何在不复制和保留源 std::string 对象的情况下获得 std::string char 数据的所有权? (我想在不同类型之间使用移动语义。)
基本上我想做一些与此等效的事情:
{
std::string s(“Possibly very long user string”);
const char* mine = s.c_str();
// 'mine' will be passed along,
pass(mine);
//Made-up call
s.release_data();
// 's' should not release data, but it should properly destroy itself otherwise.
}
为了澄清,我确实需要进一步摆脱 std::string: 。该代码同时处理字符串和二进制数据,并且应该以相同的格式处理它。我确实想要来自 std::string 的数据,因为它来自另一个与 std::string 一起工作的代码层。
为了更深入地了解我想要这样做的地方:例如,我有一个异步套接字包装器,它应该能够从用户那里获取 std::string 和二进制数据进行写入。两个“API”写入版本(采用 std::string 或行二进制数据)在内部解析为相同的(二进制)写入。我需要避免任何复制,因为字符串可能很长。
WriteId write( std::unique_ptr< std::string > strToWrite )
{
// Convert std::string data to contiguous byte storage
// that will be further passed along to other
// functions (also with the moving semantics).
// strToWrite.c_str() would be a solution to my problem
// if I could tell strToWrite to simply give up its
// ownership. Is there a way?
unique_ptr<std::vector<char> > dataToWrite= ??
//
scheduleWrite( dataToWrite );
}
void scheduledWrite( std::unique_ptr< std::vecor<char> > data)
{
…
}
std::unique_ptr 在这个例子中说明所有权转移:任何其他具有相同语义的方法对我来说都可以。
我想知道这种特定情况的解决方案(使用 std::string char 缓冲区)以及字符串、流和类似一般问题的此类问题:在字符串、流、std 容器和缓冲区类型之间移动缓冲区的技巧.
在不复制的情况下在不同 API/类型之间传递缓冲区数据时,我还希望获得有关 C++ 设计方法和特定技术的提示和链接。我提到但没有使用流,因为我在那个主题上很不稳定。
【问题讨论】:
-
你不能,因为你无法安全地回收内存。在某一时刻你应该释放缓冲区,那么为什么不将字符串一直保持下去,它会自动执行此操作?
-
std::unique_ptr<char[]>将是唯一允许类似的东西。 -
@minsk :我认为每个人都清楚你的方案,但你没有明白 - 这是不可能的。 ;-]
-
@minsk : 呃,
size()或length()- 它们都不关心嵌入的空值(如果你想要可靠的信息,请使用 cppreference 而不是 cplusplus.com :-]) . -
@minsk : C++ 标准 说 you 是错误的; §21.4.4/1:“返回:当前字符串中类似字符的对象的数量。”你不应该依赖单一的实现来获得正确的行为,你应该依赖强制行为的标准;标准库实现也有错误!
标签: c++ string c++11 buffer iostream