Creates a Cord that takes ownership of external string memory.
Declared in <absl/strings/cord.h>
template<typename Releaser>
Cord
MakeCordFromExternal(
std::string_view data,
Releaser&& releaser);
The contents of data are not copied to the Cord; instead, the external memory is added to the Cord and reference-counted. This data may not be changed for the life of the Cord, though it may be prepended or appended to.
MakeCordFromExternal() takes a callable "releaser" that is invoked when the reference count for data reaches zero. As noted above, this data must remain live until the releaser is invoked. The callable releaser also must:
* be move constructible * support void operator()(absl::string_view) or void operator()()
Example:
Cord MakeCord(BlockPool* pool) { Block* block = pool->NewBlock(); FillBlock(block); return absl::MakeCordFromExternal( block->ToStringView(), [pool, block]v) { pool->FreeBlock(block, v); }); }
WARNING: Because a Cord can be reference-counted, it's likely a bug if your releaser doesn't do anything. For example, consider the following:
void Foo(const char* buffer, int len) { auto c = absl::MakeCordFromExternal(absl::string_view(buffer, len), {});
// BUG: If Bar() copies its cord for any reason, including keeping a // substring of it, the lifetime of buffer might be extended beyond // when Foo() returns. Bar(c); }
A Cord referencing the external memory.
| Name | Description |
|---|---|
| Releaser | The callable type invoked when the data is released. |
| Name | Description |
|---|---|
| data | The external memory the Cord takes ownership of. |
| releaser | The callable invoked once the reference count reaches zero. |