2

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)

1 Answer 1

5

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.

3
  • Yes! It worked for me, despite not knowing whether my compiler is completely c++11 compliant yet. I guess it's close enough, anyway.
    – Chap
    Dec 3, 2013 at 5:07
  • I believe clang-500.2.79 is mostly c++11 compliant. You may need to compile with -stdlib=libc++ in addition to -std=c++11
    – user425495
    Dec 3, 2013 at 5:09
  • Tried with -stdlib=libc++ in addition. No difference that I can see; still works.
    – Chap
    Dec 3, 2013 at 5:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.