Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to pass a newly constructed object by reference to a function?

Tags:

c++

Specifically, is the following legal C++?

class A{};

void foo(A*);
void bar(const A&);

int main(void)
{
    foo(&A());  // 1
    bar(A());  // 2
}

It appears to work correctly, but that doesn't mean it's necessarily legal. Is it?

Edit - changed A& to const A&

like image 474
Adam Rosenfield Avatar asked Sep 17 '08 15:09

Adam Rosenfield


People also ask

Can you pass an object by reference?

A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value. “Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.

Are objects in C++ passed by reference?

C++ makes both pass by value and pass by reference paradigms possible. You can find two example usages below. Arrays are special constructs, when you pass an array as parameter, a pointer to the address of the first element is passed as value with the type of element in the array.

Does passing by reference save memory?

When an object (or built-in type) is passed by reference to a function, the underlying object is not copied. The function is given the memory address of the object itself. This saves both memory and CPU cycles as no new memory is allocated and no (expensive) copy constructors are being called.

What are the advantages of passing a vector by reference?

Here are some advantages of passing by reference: No new copy of variable is made, so overhead of copying is saved. This Makes program execute faster specially when passing object of large structs or classes. Array or Object can be pass.


1 Answers

1: Taking the address of a temporary is not allowed. Visual C++ allows it as a language extension (language extensions are on by default).

2: This is perfectly legal.

like image 141
James Hopkin Avatar answered Sep 29 '22 12:09

James Hopkin