Forums before death by AOL, social media and spammers... "We can't have nice things"
|    comp.lang.c++.moderated    |    Moderated discussion of C++ superhackery    |    33,346 messages    |
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
|    Message 33,300 of 33,346    |
|    Martin B. to Florian Weimer    |
|    Re: rvalue-reference-with-default instea    |
|    30 Mar 14 11:07:22    |
   
   From: 0xCDCDCDCD@gmx.at   
      
   On 14.03.2014 17:22, Florian Weimer wrote:   
   > It is possible to use an rvalue reference with a default argument   
   > instead of a regular named return value, like this:   
   >   
   > std::string   
   > readlink(const char *path, std::string &&result = std::string())   
   > {   
   > char buf[PATH_MAX];   
   > ssize_t ret = readlink(path, buf, sizeof(buf));   
   > if (ret < 0) {   
   > throw unistd_exception();   
   > }   
   > result.assign(buf, ret);   
   > return result;   
   > }   
   >   
   > (With C++98, you'd have to use a const reference and cast away   
   > constness.)   
   >   
   > As a result, a caller can use the default (and a completely new string   
   > object will be allocated), or it can re-use an existing string object   
   > for the return value.   
   >   
      
   I think that's an interesting idea. Basically an optional reusable buffer for   
   the caller, right?   
      
   I *think* Return Value Optimization will never be able to kick in, as you'd   
   need a std::move on the return value, but otherwise it may help if the   
   function is called in a tight loop.   
      
   It might be clearer to have two functions though:   
      
   void   
   readlink(const char *path, std::string &result)   
   {   
    ... your code (minus return) ...   
   }   
      
   std::string   
   readlink(const char *path)   
   {   
    std::string result;   
    readlink(path, result);   
    return result;   
   }   
      
      
   ... and /while/ we're doing premature optimization, I think even more could be   
   bought by throwing that char buf out of the window and directly pre-allocating   
   inside the string object:   
      
    result.resize(MAX_PATH);   
    ssize_t ret = readlink(path, &result[0], result.size());   
    if (ret < 0) {   
    result.clear();   
    throw unistd_exception();   
    }   
    result.resize(ret);   
    return result;   
      
   What say you?   
      
   cheers,   
   Martin   
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
(c) 1994, bbs@darkrealms.ca