Note that there are some explanatory texts on larger screens.

plurals
  1. POMove semantics and virtual methods
    text
    copied!<p>In C++11 we are guided in some cases to pass objects by value and in others by const-reference. However, this guideline depends on the <strong>implementation</strong> of the method, not just on its interface and intended usage by its clients. </p> <p>When I write an interface, I do not know how it will be implemented. Is there a good rule of thumb for writing method signatures? For example - in the following code fragment, should I use <code>Bar1</code> or <code>Bar2</code>?</p> <pre><code>class IFoo { public: virtual void Bar1(std::string s) = 0; virtual void Bar2(const std::string&amp; s) = 0; }; </code></pre> <p>You can stop reading here if you agree that the correct signature depends on the implementation. Here is an example that shows why I believe so.</p> <p>In the following example, we should pass the string by value:</p> <pre><code>class Foo { std::string bar; Foo(std::string byValue) : bar(std::move(byValue)) { } }; </code></pre> <p>Now we can instantiate Foo in an efficient manner in all cases:</p> <pre><code>Foo foo1("Hello world"); // create once, move once Foo foo2(s); // the programmer wants to copy s. One copy and one move Foo foo3(std::move(t)); // the programmer does not need t anymore. No copy at all </code></pre> <p>In other cases we prefer to pass objects by const reference. For example, in the following case we never want to copy/store the argument, just use its methods:</p> <pre><code>void DoStuff(const std::string&amp; byRef) { std::cout &lt;&lt; byRef.length() &lt;&lt; std::endl; } </code></pre> <p>All possible usages of the above method are already as efficient as possible.</p> <p><strong>Update</strong></p> <p>I believe I forgot to show the issues with the const-reference alternative. If the above class <code>Foo</code> was implemented this way:</p> <pre><code>class Foo { std::string bar; Foo(const std::string&amp; byRef) : bar(byRef) { } }; </code></pre> <p>Then we would have the following results:</p> <pre><code>Foo foo1("Hello world"); // Here we would have one more copy of the string. It is less efficient. Foo foo2(s); // One copy, like before Foo foo3(std::move(t)); // Irrelevant here. </code></pre> <p>Alex.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload