Questions tagged [return-value-optimization]

C++ copy-elision of return-values.

Filter by
Sorted by
Tagged with
0 votes
0 answers
55 views

Is passing the uninitialized variable to function considered UB in C++? [duplicate]

Recently I was writing my raytracer project and made some bugs in it. I have a function: double Length(const Vector& v) { return std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); } and then ...
Greg's user avatar
  • 19
3 votes
2 answers
113 views

Why isn't named return value optimization working here?

I know that I have deleted the copy constructor, I was assuming that was OK since I was expecting named return value optimization and that direct initialisation would happen. Does the copy constructor ...
Zebrafish's user avatar
  • 12.1k
1 vote
1 answer
58 views

Why cant copy elision take place when a 'by-value' parameter is also the 'by-value' return argument? [duplicate]

In the following code snippet my function tries to return it's 'by-value' argument as a 'by-value' return-value. I watched a video where it stated: "It is physically not possible to do copy ...
EL IAS's user avatar
  • 23
1 vote
3 answers
166 views

How to enforce copy elision in C++20? [duplicate]

C++17 promised to introduce Copy Elision as a requirement, so I've upgraded from C++14 all the way to C++20. Just for that. (RVO as an optional behavior-altering optimization... makes me genuinely ...
Anne Quinn's user avatar
  • 12.7k
-1 votes
2 answers
158 views

Operator overloading: Modify temporary object or create new one

I've seen the following code in our project and asked myself what are the technical and mental implications: class A { public: A(const A&); A(A &&); ~A(); A &operator +...
phlipsy's user avatar
  • 2,929
0 votes
3 answers
90 views

Custom static cast function template in C++14

I've written such a template function for static casting as kind of an exercise: template<typename cT, typename T> inline constexpr cT sCast(T carg) { return static_cast<cT>(carg); } ...
spdie's user avatar
  • 13
1 vote
0 answers
55 views

Returning std::unique_ptr<> in a register. Can it be done? [duplicate]

In the ARM procedure call standard for the 32-bit architecture, it is possible to return a struct with a single data member in a register, rather than on the stack. The size of a C++ unique_ptr is ...
sh-'s user avatar
  • 991
2 votes
3 answers
76 views

C++ return by value class objects's memory whereabouts in wake of optimizations

Let's say there is a user defined class Foo. Some posts suggest that a C++ class object is "never" allocated on heap unless allocated with new. But! on the other hand there are posts that ...
codepoet's user avatar
  • 154
6 votes
1 answer
138 views

Why does C++ compilation for named return value optimization fail when the copy or move constructor is deleted?

I tried the following on gcc 13.1 on C++ on C++11/17/20/23 but it fails to compile when the move or copy constructor is deleted. If those constructors are not deleted, then named return value ...
Nathan Doromal's user avatar
0 votes
1 answer
124 views

Does it work when a reference refers to a function's return value?

class AA { private: string s = "asd"; public: string func1() { return s; } string& func2() { return s; } }; func1() returns a copy and func2() ...
f1msch's user avatar
  • 579
3 votes
2 answers
97 views

Does a temporary shared_ptr returned by value have the counter incremented?

I'm trying to understand how RVO works in conjunction with shared_ptr in this particular case. Let's say I have this example code: class A { public: void action() {} }; class Container { public: ...
Mix Kira's user avatar
  • 107
0 votes
1 answer
54 views

Taking address of RVO-optimized static

In the following code I try to register a singleton instance with a global array that keeps all singletons (in production code I can instantiate different singletons based on template parameters so ...
glades's user avatar
  • 3,915
0 votes
1 answer
102 views

When in C++14 with RVO/NRVO closed, how is the object returned?

I am learning about move semantics, so I wrote a small program as follows to practice: #include <iostream> using namespace std; int one_int = 123; class A { public: int *a; A(int *...
Isuxiz Slidder's user avatar
0 votes
1 answer
120 views

Destructor called twice with Return Value Optimization

In order to understand copy elision I wrote a small example #include "iostream" using namespace std; struct Foo { Foo() { cout << "constructor was called" << endl;...
roi_saumon's user avatar
2 votes
0 answers
103 views

MSVC: why calling a static function generates more assembly code than calling an instance method?

When disassembling my application, I have noticed that MSVC generates more assembly opcodes when I'm calling a static method compared to an instance method. This is true even when both functions are ...
Laurent's user avatar
  • 2,959
2 votes
1 answer
156 views

NRVO. Turning off elision. C++11 vs C++17

I am looking at copy elision and RVO/NRVO. When I run g++ with -fno-elide-constructors I see different behaviour for c++11 and c++17. I understand that c++17 mandates RVO under certain circumstances. ...
TCD's user avatar
  • 151
0 votes
1 answer
37 views

Dynamic Response doesn't return the property tag which is assigned null. I need the element in the response atleast

I have a post API with a return type as Dynamic. I return a class object after processing my logic. There are cases when I need to assign null to certain properties in the class object. When this is ...
Alisha Das's user avatar
0 votes
0 answers
43 views

How to ensure a function avoids copying a returned value in C++17 [duplicate]

I've always avoided returning objects by value, due to copy-elision being an optimization with observable side-effects... but I've read that C++17 has added a way to ensure returned objects never call ...
Anne Quinn's user avatar
  • 12.7k
0 votes
3 answers
214 views

When to rely on RVO vs move semantics in C++?

Say I have some expensive class X, and take this code: X functor() { X x; //do stuff return x; } int main() { std::vector<X> vec; vec.push_back(functor()); vec.push_back(...
TwistedBlizzard's user avatar
1 vote
1 answer
91 views

Is the C++ NVRO applicable with object slicing or with a local object data member?

Copy elision starts to become more and more mandatory with each new C++ standard. However, the conditions into which it is applicable are not always obvious and I need help to better understand them ...
lano1106's user avatar
  • 158
3 votes
2 answers
120 views

Why can't the C++ compiler elide the move when moving a POD into an optional with RVO?

Consider the following code (godbolt): #include <optional> #include <array> struct LargeType { std::array<int, 256> largeContents; }; LargeType doSomething(); std::optional<...
gexicide's user avatar
  • 38.9k
1 vote
2 answers
436 views

Why C++ does not perform RVO to std::optional?

I am wondering why C++ does not perform RVO to std::optional<T> when returning T. I.e., struct Bar {}; std::optional<Bar> get_bar() { return Bar{}; // move ctor of Bar called here ...
Bin Yan's user avatar
  • 129
0 votes
0 answers
56 views

Returning address of the rvalue input to function

Today when reading a project's source code I came across an interesting example. In this example a template function's taking T&& and returning it back as T& after it's job done. This ...
user avatar
1 vote
0 answers
69 views

Are function-local objects guaranteed to be returned as rvalue-references? [duplicate]

In the following simple code I return a function local object from a function (factory function). Does the C++ standard guarantee in every case that this object is being returned as an rvalue ...
glades's user avatar
  • 3,915
0 votes
0 answers
49 views

Why return by reference disables NRVO [duplicate]

I was testing out the Return Value Optimizations in C++ Visual Studio 2022. I was surprised that the following program needed to call the copy constructor: #include <iostream> class A { public: ...
Chandrachur Mukherjee's user avatar
17 votes
3 answers
732 views

Why doesn't RVO happen with structured bindings when returning a pair from a function using std::make_pair?

Consider this code, which defines a simple struct Test (with a default constructor and copy constructor) and returns a std::pair <Test, Test> from a function. #include <iostream> #include &...
Christopher Miller's user avatar
3 votes
1 answer
830 views

Does returning a local variable return a copy and destroy the original(nrvo)?

I saw this question When is an object "out of scope"? I have taken a look at the sparc_spread's answer and I found one problem in it. In this section of his answer: Circle myFunc () { ...
f877576's user avatar
  • 463
0 votes
0 answers
147 views

Return Value Optimization in C++

I have the following code: struct return_values { std::shared_ptr<SomeType> a; std::shared_ptr<SomeType> b; std::shared_ptr<SomeType> c; }; return_values foo() { std:...
Tox's user avatar
  • 1
1 vote
2 answers
385 views

Returning a pair of objects

The following is an anti-pattern: auto f() { std::vector<int> v(100000); return std::move(v); // no need to use std::move thanks to RVO (return value optimization) } Using a std::move can ...
Bérenger's user avatar
  • 2,678
1 vote
1 answer
174 views

Why can't I return an object that has a move constructor but whose copy constructor is explicitly deleted?

I have a functor whose declaration looks like this: class logger { public: log_t operator() (unsigned _LogLevel) { return log_t{_LogLevel}; } }; As in the code, I want this functor to ...
依奈ちゃん's user avatar
1 vote
1 answer
434 views

Returning Eigen matrices and temporaries

Consider the following function Foo: // ... Eigen::Vector3d Foo() { Eigen::Vector3d res; // ... return res; } int main () { Eigen::VectorXd foo = Foo(); // (1) return 0; } ...
fdev's user avatar
  • 147
1 vote
0 answers
48 views

Idiomatic way of returning 2 values [duplicate]

What is the modern approach when it comes to returning two values (e.g. a vector and a bool)? This one: bool tokenize( const std::string_view inputStr, const std::size_t expectedTokenCount, ...
digito_evo's user avatar
  • 3,276
0 votes
0 answers
67 views

RVO or move for std::list

I have the following implementation which returns the last element of a std::list<T> and deletes it from the list: std::list<T> list_; T ReturnAndDeleteLast( )const { T last( ...
ATK's user avatar
  • 1,316
2 votes
0 answers
122 views

NRVO of std::array in constructor initialiser list

I know std::array doesn't do move semantics because it's not dynamically allocated. Do Compilers do proper NRVO for it? What about in the context of the calling code being a constructor initializer ...
Oliver Schönrock's user avatar
2 votes
1 answer
73 views

Efficiently creating a class inside a class method and passing it out of there?

CList<CString> Split(char delim) { CList<CString> subStrings; for (char* ps = Buffer(); *ps; ps++) { char* pe; for (pe = ps; *pe && (*pe != ...
Razzupaltuff's user avatar
  • 2,250
1 vote
2 answers
89 views

Returning an object by value which should conceptually not be copied

I'd like to have an object whose constructor acts as a begin() and it's destructor acts as an end(), and provides functions that are only valid between these two calls as methods. However... I also ...
Anne Quinn's user avatar
  • 12.7k
38 votes
2 answers
2k views

Why is public destructor necessary for mandatory RVO in C++?

Please consider the simple example as follows, where the function bar returns an object of class A with private destructor, and mandatory return value optimization (RVO) must take place: class A { ~A()...
Fedor's user avatar
  • 17.6k
1 vote
1 answer
283 views

Can I always rely on RVO by the compiler?

I have a function for reading files into a string variable. And I am not sure what is a better way to implement it: void readFile(const std::filesystem::path& path, std::string& ...
Alexey104's user avatar
  • 989
2 votes
1 answer
261 views

What is performance penalty for using aggregates in C++?

Consider this example with a structure S constructed and passed as an argument to a function: struct S { S() {} float vals[64]; }; inline S makeS() { return {}; } void foo(const S &); ...
user avatar
23 votes
1 answer
601 views

What happens when mandatory RVO is applied to a reference that's extending the lifetime of a temporary?

When a reference is initialized with another reference that's extending the lifetime of a temporary, this new reference doesn't extend anything. But what happens when mandatory RVO prevents the ...
HolyBlackCat's user avatar
  • 82.9k
2 votes
2 answers
217 views

Copy elision and operator overloading with C++

I have a struct such as: struct A { double x,y; vector<double> vec; }; I would like to overload operators such as the plus operator so that I can perform operations such as: A a,b,c,...
pah52's user avatar
  • 85
6 votes
3 answers
195 views

Is std::declval outdated because of guaranteed copy elision?

The standard library utility declval is defined as: template<class T> add_rvalue_reference_t<T> declval() noexcept; To add a rvalue reference here seemed like a good idea, if you think ...
Tobi's user avatar
  • 2,621
2 votes
0 answers
156 views

RVO or automatic move

Consider the following function. std::string foo() { const std::string s = "hello"; return s; } clang-tidy suggests to remove const qualifier as is prevents an automatic move. Is this ...
Anubis's user avatar
  • 7,125
3 votes
1 answer
200 views

Why does non-trivial destructor of return type prevent tail-call optimization?

Currently, in C++ compilers one of the rules for tail-call optimization is that the return type must be trivially destructible. (Based on analyzing GCC, Clang trunk behavior. MSVC has troubles with ...
Kaznov's user avatar
  • 1,045
12 votes
2 answers
392 views

Unintuitive RVO of function returning non-copyable const value?

Consider the following example code in C++ >=17: struct A{ A() = default; A(const A&) = delete; }; const A f(){ return A{}; } int main(){ const A& a = f(); // OK // A& ...
eivour's user avatar
  • 1,698
4 votes
1 answer
294 views

Return value optimization for string_view inside shared_ptr

It's hard to put into words so I will directly jump into a semi-pseudo-code. I have a download function (http GET), that is being called many many times inside my main code. std::string download_data()...
Max Paython's user avatar
  • 1,593
1 vote
1 answer
68 views

If a variable is assigned an object returned by a function, is it copied or created in-place?

I have something like this in my CPP file to initialize an object outside any class. I've simplified it but the point is there is some complex initialization going on but I want a single instance ...
Mr. Boy's user avatar
  • 61.4k
1 vote
2 answers
189 views

Does NRVO happen in static member variables initialization?

I have got a class with a large static std::array that needs an expensive computation to be initialized, so i defined a static method to perform it. I don't know however if some copy happens or maybe ...
lucmobz's user avatar
  • 463
1 vote
1 answer
1k views

How does C++ return value optimization (RVO) work when the function get's called with the variable that the return value gets assigned to?

Originally, I had a problem like this: I have a vector with data and want to perform an operation n times. Doing it in place is impossible, so a new vector gets constructed in every loop cycle, the ...
Kingsly2407's user avatar
0 votes
0 answers
102 views

How to return a value from a function in an efficient way? (c++)

I am not a professional CS programmer. I wrote a function to calculate displacement between two images. The function looks like this. void myFunction(Mat img1, Mat img2) { do some calculation; } ...
MisakaMisaka's user avatar