logo
down
shadow

C++: RVO, NRVO and returning local objects


C++: RVO, NRVO and returning local objects

By : user2956545
Date : November 22 2020, 10:56 AM
Hope this helps I just read about RVO (Return Value Optimization) and NRVO (Named Return Value Optimization). Below are two examples , They are different.
code :
Bar Foo();
const string &manip();


Share : facebook icon twitter icon
Returning automatic local objects in C++

Returning automatic local objects in C++


By : Franchoiss
Date : March 29 2020, 07:55 AM
Hope this helps
Is makeNewCarCopy safe? Is the local object being copied and destroyed at the end of the function? If so, why isn't it calling the overloaded assignment operator? Does it call the default copy constructor?
Why does the returned value need to be the first declared local for NRVO?

Why does the returned value need to be the first declared local for NRVO?


By : user2768955
Date : March 29 2020, 07:55 AM
it should still fix some issue The standard imposes no requirements on the order of declarations/definitions for variables in regards to copy elision. Note that the standard says "an implementation is allowed", not that it should, shall, etc. We can see that copy elision occurs for clang and gcc, but not MSVC, further cementing that this is an implementation-defined optimization.
§12.8/31 describes copy elision:
Shouldn't NRVO guarantee the local named variable and the call-site variable to take the same address?

Shouldn't NRVO guarantee the local named variable and the call-site variable to take the same address?


By : Richar Flores
Date : March 29 2020, 07:55 AM
it helps some times Definitely seems to be a bug in clang, they should be the same, else things like the following will be erroneous
code :
struct S
{
    int i;
    int* ptr;

    S(int i) : i(i) {
        this->ptr = &this->i;
    }

    S(S&& s)
    {
        this->i = s.i; 
        this->ptr = &this->i;
        std::cout << "S(S&&)\n";
    }

    S(S const&) = delete;
};
Does returning a default constructed object prevent NRVO?

Does returning a default constructed object prevent NRVO?


By : Mint13 Linux User
Date : March 29 2020, 07:55 AM
With these it helps As requested by the OP, here is an adapted version of my comment
I was actually wondering the same thing (especially since copy elision is not "required" by the standard), so I tested it quickly in an online compiler by replacing std::vector by a Widget struct:
code :
struct Widget
{
    int val = 0;
    Widget()              { printf("default ctor\n"); }
    Widget(const Widget&) { printf("copy ctor\n"); }
    Widget(Widget&&)      { printf("move ctor\n"); }

    Widget& operator=(const Widget&) { printf("copy assign\n"); return *this; }
    Widget& operator=(Widget&&)      { printf("move assign\n"); return *this; }

    ~Widget() { printf("dtor\n"); }

    void method(int)
    {
        printf("method\n");
    }
};
#include <cstdio>
#include <array>
#include <cstdlib>

using std::array;

struct Widget
{
    int val = 0;
    Widget()              { printf("default ctor\n"); }
    Widget(const Widget&) { printf("copy ctor\n"); }
    Widget(Widget&&)      { printf("move ctor\n"); }

    Widget& operator=(const Widget&) { printf("copy assign\n"); return *this; }
    Widget& operator=(Widget&&)      { printf("move assign\n"); return *this; }

    ~Widget() { printf("dtor\n"); }

    void method(int)
    {
        printf("method\n");
    }
};

bool some_condition(int x)
{
    return (x % 2) == 0;
}

array<int, 3> something()
{
    return {{1,2,3}};
}

Widget build_vector(int n)
{
   if (some_condition(n)) return {};

   Widget out;

   for(int x : something())
   {
      out.method(x);
   }

   return out;
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        return -1;
    }
    const int x = atoi(argv[1]);

    printf("call build_vector\n");
    Widget w = build_vector(x);
    printf("end of call\n");
    return w.val;
}
call build_vector
default ctor
method
method
method
move ctor
dtor
end of call
dtor
#include <cstdio>
#include <array>
#include <cstdlib>

using std::array;

struct Widget
{
    int val = 0;
    Widget()              { printf("default ctor\n"); }
    Widget(const Widget&) { printf("copy ctor\n"); }
    Widget(Widget&&)      { printf("move ctor\n"); }

    Widget& operator=(const Widget&) { printf("copy assign\n"); return *this; }
    Widget& operator=(Widget&&)      { printf("move assign\n"); return *this; }

    ~Widget() { printf("dtor\n"); }

    void method(int)
    {
        printf("method\n");
    }
};

bool some_condition(int x)
{
    return (x % 2) == 0;
}

array<int, 3> something()
{
    return {{1,2,3}};
}

Widget nrvo_friendly_build_vector(int n)
{
   Widget out;

   if (some_condition(n)) return out;

   for(int x : something())
   {
      out.method(x);
   }

   return out;
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        return -1;
    }
    const int x = atoi(argv[1]);

    printf("call nrvo_friendly_build_vector\n");
    Widget w = nrvo_friendly_build_vector(x);
    printf("end of call\n");
    return w.val;
}
call nrvo_friendly_build_vector
default ctor
method
method
method
end of call
dtor
Returning tuple of local objects

Returning tuple of local objects


By : Bren
Date : March 29 2020, 07:55 AM
I wish this helpful for you
I want the bindings in the last line to reference the objects inside of owner.
code :
int&& f() { return 0; }
int&& r = f();
int global = 0;
int&& f() { return std::move(global); }
int&& r = f(); // okay, r is a reference to global, no dangling
int f() { return 0; }
int&& r = f(); // okay, lifetime extension
int i = f();   // okay, prvalue elision
struct X {
    X() : owner(controller, ancillary, compressor) { }
    X(X const&) = delete;
    X& operator=(X const&) = delete;

    State<Controller> controller;
    State<Ancillary>  ancillary;
    State<Compressor> compressor;
    Owner owner;        
};

// lifetime extension on the X, no copies anywhere
// note that owner is last
auto&& [controller, ancillary, compressor, owner] = X();

// no lifetime extension, but also no copies because
// prvalue elision
auto [controller, ancillary, compressor, owner] = X();
Related Posts Related Posts :
  • Vector of pointers: some clarification needed
  • scaling a bitmap without losing quality
  • How to evaluate a function directly?
  • QNetworkAccessManager: How to change post data at createRequest function
  • Returning std::move of a local variable
  • Is there a fast linear SVM library with a good C++ interface?
  • What is the purpose of name mangling in C++?
  • C++ Why the void function is not working eventhough I called it?
  • How the pointer and the pointer's adress can share the same memory adress?
  • error C2220: warning treated as error - no 'object' file generated
  • exception of strcpy function in c++ console program
  • How to access USB barcode scanner data directly from USB port using C/C++ without driver
  • Under which circumstances will std::vector.clear() call a destructor?
  • Template partial specialisation and dependent names
  • best way to share data between c codes
  • C++ ignores if statement conditions
  • How to set the argv[ ] to be case-insensitive in a Win32 Console Application?
  • How to fix error "clang: error: linker (via gcc) command failed with exit code 1 (use -v to see invocation)"?
  • C++ How do I print a .txt file verbatim?
  • Creating two dimensional array of class
  • How do I correctly use COMMTIMEOUTS with OVERLAPPED IO mode reading from a Serial port
  • An assert macro which expands to static_assert when possible?
  • How to write a copyconstructor for a class which has HANDLE as a member in win32 c++ application?
  • C++ saving info such as tree in a file
  • Transforming an expression template tree
  • How to overload an operator with multiple parameters like a + b + c?
  • C++ 11 with Raspberry Pi performances
  • Make a C++ class look like a numpy array using swig
  • Postfix incrementer overloading for nested enumerated types
  • Is there a tidy way of associating metadata with functions in C++
  • QObject::installEventFilter(): Cannot filter events for objects in a different thread
  • LNK2005 error with Zxing C++
  • C++ Doubly Linked List with Pointers: Object of class isn't constructed properly
  • Using a random string generator in c++ constructor
  • What should I use instead of void as one of the alternative types in an variant?
  • C++ return value from multithreads using reference
  • How to connect multiple TCP IP clients to same server port using c++
  • Defaul compiler generates the reference operator (In C++)?
  • Unable to change directory time stamp after using FILE_FLAG_BACKUP_SEMANTICS
  • vector handling displaying output
  • WSAGetLastError returns WSAENOTSOCK - Cause?
  • C++: How to overload pow for user type?
  • C++ using arrays as multidimensional despite initalising it as 1D with pointer
  • How negate std::is_integral for use in tag dispatch?
  • Retrieve serial number from USB memory (Windows environment c++)
  • g++ error: invalid preprocessing directive #INCLUDE
  • C++ What is the std::for_each() function parameter type?
  • C++: Read individual lines from text file, sort words alphabetically
  • Saving 'this' address into a variable
  • c++ command line arguments in ubuntu terminal
  • Convert "Cartesian coordinates" to "polar coordinates with respect to user specified origin"
  • In what order are local scoped objects destructed?
  • How to use SDL_MapRGB with SDL 2.0
  • how compiler and interpreter work in case of array declaration
  • GSL integration behaves strange
  • Cropping an image with OpenCV and C
  • Find the last line in text file and select the first 10 char and print to a new file?
  • Created many CCSprits but when triggering ccTouchBegan gives the last one allways
  • seekp and seekg don't work with fstream
  • Taking input in Sublime Text 3
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org