bochaltura
bochaltura

Reputation: 287

Is it legal to hold reference/pointer to the return object value of a function?

Is it legal to pass the return object of the function by value? I have a function from A::getA() that returns an object by value. Is it legal to reference this value in the same line, see the line b.processA(a.getA());

Please see my code below:

class A
{
public:
    int a;
    std::list<int*> m_list;

    A(int a)
    {
        this->a =a;
    }

    A(A& _a)
    {
        this->a =_a.a;
        m_list.push_back(&a);
    }

    A getA()
    {
        A localA(20);
        localA.m_list.push_back(&localA.a);
        return localA;
    }
};

class B
{
public:
    char b;

    B(char b)
    {
    }

    void processA(A& a)
    {
            a.a = 1;
            processA2(a);
    }

    void processA2(A& a)
    {
        a.a = 2;
    }
};

void main()
{
    B b('a');
    A a(11111);
    //************
    // IS THE FOLLOWING LINE LEGAL??
    // I mean, is it legal to pass the return object of the function by value
    //************
    b.processA(a.getA());
}

Upvotes: 0

Views: 116

Answers (2)

Andrew Tomazos
Andrew Tomazos

Reputation: 68688

So basically you are asking if:

X f();
void g(X& x);

g(f());

is legal or not?

As a safety precaution a noncost reference can't bind to a temporary. So the above is not legal.

However the following is legal:

X f();
void g(const X& x);

g(f());

The temprary will survive until g returns.

The reason the first version is llegal is because any changes made by g will be discarded, so why would you want that? It most likely indicates a logical error, so as a language design decision it was made a compile-time error.

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361532

b.processA(a.getA());

No. It will not even compile. The reason is thata.getA() returns a temporary object, which cannot be bound to non-const reference type.

However, if you make the parameter const reference as:

void processA(A const & a) 

then it is fine.

Note: MSVC++ provides temporary-object binding to non-const reference as extension. It is not Standard.

Upvotes: 3

Related Questions