MemRef is a small object that contains a pointer to memory, and a length. It's central to an optimization project to minimize string copying in a critical section. tokens is a deque<MemRef>.

As I identify tokens in an input buffer, I want to construct MemRefs and add them to the token deque. First try was:

MemRef foo(token_begin, token_len);
tokens.push_back( foo );

Since I saw dtor calls here, it clued me that foo was being created, copied, and then destroyed. Next try was:

tokens.push_back( MemRef(token_begin, token_len) );

But I saw the same behavior. My guess is that a temporary is being created, copied into the deque, and then destroyed, and that perhaps this is where the subject of "move semantics" comes in (which I'm very unclear about).

Is there a way to, in effect, construct the MemRef directly into the tokens deque, without creating and destroying a temporary?

(I'm using Apple LLVM version 5.0 (clang-500.2.79) with --std=c++11)

有帮助吗?

解决方案

Use emplace_back:

tokens.emplace_back(token_begin, token_len);

This will construct a MemRef in-place. Note that this is only available with c++11.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top