Let us have a complex class with two double data member.
If I would like to copy it by reference
that means that I have two copy one or two pointers?

Dani AI

Generated

Brief answer for (and following up on ): passing a small Complex that holds two double members by value copies those two doubles (typically 16 bytes). Passing by reference does not copy the doubles; it passes a reference. Implementations commonly represent a reference as a single pointer-sized word (one machine word), not two pointers. The standard does not mandate the exact representation, so think of a reference as "one indirection" in practice.

Performance guidance: for tiny, trivially-copyable types like two doubles, modern compilers and ABIs often pass them in registers, so passing by value can be as cheap or cheaper than passing by reference because it avoids extra indirection. For larger or non-trivial objects, prefer const reference to avoid expensive copies. If a local copy is required and you expect moves, the "pass by value and move" pattern is useful in modern C++.

How to decide in your build:

  • Check sizeof(Complex) and whether it is trivially copyable.
  • Inspect generated code (compile with optimizations and view assembly) to see whether the compiler uses registers or memory.
  • Remember lifetime rules: as noted, returning or storing references must not outlive the referent.

Example check (compile and run to see size and triviality):

#include <type_traits>
#include <iostream>

struct Complex { double re, im; };

int main() {
    std::cout << sizeof(Complex) << '\n';
    std::cout << std::boolalpha
              << std::is_trivially_copyable<Complex>::value << '\n';
}

Recommended Answers

All 2 Replies

In C++ term of reference or in general ?

You can do this :

Complex& Complex::getClass() { return *this; }

That way, you get the Complex class as a reference in terms of the reference operator.

No, my question is not the syntax!
My question is about the compiling and the speed!
So if I have a function:

void function(complex c);

or

void function(complex& c);

works faster?
In the second case, only one or two pointer are copied?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.