C++: use returned object from function - c++

To use returned object from functions, could anyone tell me why case 1, 3, 4 are OK but not 2 in this code?
#include <iostream>
using namespace std;
class X {
int i;
public:
X(int ii = 0) : i(ii) {};
void modify() { i++; };
};
X f1() { return X(1); }
// Pass by non-const reference
void f20(X& x) { x.modify(); }
// Pass by const reference
void f21(const X& x) { }
// Pass by value
void f22(X x) { x.modify(); }
int main() {
f1() = X(2); // 1. OK
//! f20(f1()); // 2. Bad
f21(f1()); // 3. OK
f22(f1()); // 4. OK
}
Thank you!

Because temporaries can't be bound to lvalue reference to non-const.
The main rationale I've seen bandied about is that otherwise (as with the Visual C++ language extension) a function like
void increment( int& value ) { ++value; }
might be called like
auto main() -> int
{
increment( 2+2 );
}
but I'm not sure that's entirely convincing.
The rules do help with much coding, but as the Visual C++ language extension (allowing the binding for class types) exemplify, it's not crucial and not much an issue in ordinary code.
In passing, note that a temporary object is not const, unless it has been declared as such. In particular you can call non-const member functions on it, like in your case f1().modify(). You just can’t bind it to an lvalue reference to non-const.

The f1() method returns the temporary object of type X.
The = operator can be applied to the object of type X, even though the object itself is not going to be available afterwards.
f21() expects const reference (i.e. something that isn't supposed to change within that function) so there is no check whether the reference is valid.
f22() expects the value itself, which is modified inside the function and then the modifications are lost.
f20() expects a reference, i.e. the changes which are made inside this function are supposed to apply to the object that exists outside of that function. But it gets a reference to a temporary object, therefore the problem.
If you want to return the reference to the non-temporary object, your function would have to look like:
X& f1() { return *(new X(1)); }
and you'll have to take care of deleting this object afterwards.

Related

Is repeatedly calling move with rvalue references necessary?

struct Bar
{
Bar(std::string&& val)
: m_Val(std::move(val)) {} // A
Bar& operator=(Bar&& _other) { m_Val = std::move(_other.m_Val); }
std::string m_Val;
}
struct Foo
{
void Func1(Bar&& param)
{
Func2(std::move(param)) // B
}
void Func2(Bar&& param)
{
m_Bar = std::move(param); // C
}
Bar m_Bar;
};
void main()
{
Foo f;
std::string s = "some str";
Bar b(std::move(s));
f.Func1(std::move(b));
}
Give that you're calling move in main() to invoke the rvalue reference methods, is it necessary in lines A & B & C to repeat an additional call to move()? You already have the rvalue reference, so is it doing anything different in those lines with vs without?
I understand in Bar's operator= it's necessary because you're technically moving the m_Val rather than _other itself correct?
Note: Originally, I was incorrectly calling rvalue references as rvalue parameters. My apologies. I've corrected that to make the question easier to find and make clearer.
Give that you're calling move in main() to invoke the rvalue parameter methods, is it necessary in lines A & B & C to repeat an additional call to move()?
Yes. What you call an rvalue parameter is actually an rvalue reference. Just like a lvalue reference, it is an lvalue in the scope that it is being used. That means you need to use move to cast it back into an rvalue so that it gets moved, instead of copied. Remember, if the object has a name, it is an lvalue.

Confused about object and dereferenced pointer

I don't get the difference between passing the instance of an object to passing a dereferenced object. I have
class A
{
public:
A() {}
void m() {}
};
void method(A& a)
{
a.m();
}
int main(int argc,char** argv)
{
method(A());
return 0;
}
The call above does not work with compiler errors:
In function 'int main(int, char**)':
error:no matching function for call to 'method(A)'
note: candidates are:
note: void method(A&)
note: no known conversion for argument 1 from 'A' to 'A&'
note: void method(B&)
no known conversion for argument 1 from 'A' to 'B&'
But if I write
method(*(new A()));
it does.
Can anyone please tell my why and how to resolve the problem if I cannot change the method I want to call?
In the first case, you create a temporary object that you try to pass to method.
A temporary object cannot be modified (it doesn't make sense to modify it, it will be gone the moment method returns). So to pass a temporary by reference, you must pass by a const reference.
void method(const A& a)
{
}
Here you are creating a temporary object:
method(A()); // A() here is creating a temporary
// ie an un-named object
You can only get const& to temporary objects.
So you have two options:
Change the interface to take a const reference.
Pass a real object.
So:
// Option 1: Change the interface
void method(A const& a) // You can have a const
// reference to a temporary or
// a normal object.
// Options 2: Pass a real object
A a;
method(a); // a is an object.
// So you can have a reference to it.
// so it should work normally.
If this were legal, horrible things would happen. Consider:
void addOne(double& j) { ++j; }
int q = 10;
addOne(q);
This would create a temporary double, add one to it, and leave your original q unmodified. Ouch.
If method modifies its parameter, your code is broken. If it doesn't, it should take a const reference.
Problem that you see is that your function accepts only lvalue of type A. To solve the issue you can either change your function to accept type A by value:
void method( A a ) {}
or by const reference:
void method( const A &a ) {}
or by rvalue reference (if you use C++11):
void method( A &&a ) {}
or pass lvalue of type A to your method:
A a; method( a );
If you want to understand the problem deeper read about lvalue in c++

Is return by value always const?

This code does not compile:
class C {};
void foo (C& c) {}
C bar() { return C(); }
int main()
{
foo(bar());
}
Compilation error (GCC 4.1.2) in line foo(bar()):
invalid initialization of non-const reference of type 'C&'
from a temporary of type 'C'
As bar() returns a mutable object, it should compile...
Why C++ does not allow this above code?
EDIT: I have summarize in an answer below all good ideas from all answers ;-)
The applicable rule here is that you can't create a non-const reference to a temporary object. If foo was declared as foo(const C&) the code would be okay.
The temporary object itself is not const, though; you can call non-const member functions on it, e.g., bar().non_const_member_function().
With C++11, foo can be written to take an rvalue reference; in that case, the call would be okay:
void foo(C&&);
foo(bar()); // okay
It's because the value returned by bar is a temporary value. As it's existence is temporary, you can't use a pointer or reference to that.
However, if you store a copy of that temporary, as in your second change, you no longer pass a reference to a temporary object to foo, but a reference to a real tangible object. And in the first case, when you change to a reference to a constant object, the compiler makes sure the temporary object stays around long enough (as per the C++ specification).
The issue is not with the declaration of bar but with that of foo. foo takes a non-const reference, and temporaries can only bind to const references (which then extends the lifetime of the temporary to match that of the reference it is bound to).
Allowing a non-const reference to bind to a temporary doesn't make much sense. A non-const reference implies that it will modify whatever object is bound to it. Modifying a temporary serves no purpose since its lifetime is limited and the changes will be lost as soon as it goes out of scope.
Modifiable (lvalue-)references do not bind to temporary values. However, const-references do bind to temporary values. It has nothing to do with whether the object returned by value is const or not; it's simply a matter of whether the expression is temporary or not.
For example, the following is valid:
struct C { void i_am_non_const() {} };
int main()
{
bar().i_am_non_const();
}
It is a design choice. There is nothing inherently impossible here. Just a design choice.
In C++11, you have a third alternative which is also superior alternative:
void foo(C && c) {}
That is, use rvalue-references.
It's not const, but it is a temporary rvalue. As such, it can't bind to a non-const lvalue reference.
It can bind to a const or rvalue reference, and you can call member functions (const or not) on it:
class C { void f(); };
void foo_const(C const &);
void foo_rvalue(C &&);
foo_const( bar() ); // OK
foo_rvalue( bar() ); // OK
bar().f(); // OK
The real, hard truth is that it makes no sense to get a reference to a temporary value.
The big point of passing an object by reference is that it allows you to modify its state. However, in the case of a temporary, by its very nature, it would not be particularly helpful to be able to modify it, since you have no way of getting another reference to it later in your code to see the changes.
However, this is somewhat different in the case you have a const reference. Since you'll only ever read from a const reference, it makes total sense to be able to use temporaries there. This is why the compiler will "hack" around it for you, and give a more permanent address to temporaries that you want to "turn" into const references.
So, the rule is that you cannot get a non-const reference to a temporary value. (This slightly changed with C++11, where we have a new type of references that serve this exact purpose, but methods are expected to deal with those in a special way.)
Thank you all for your answers :-)
Here I gather your good ideas ;-)
Answer
Return by value is not const. For example, we can call non-const member functions of return by value:
class C {
public:
int x;
void set (int n) { x = n; } // non-const function
};
C bar() { return C(); }
int main ()
{
bar.set(5); // OK
}
But C++ does not allow non-const references to temporary objects.
However C++11 allow non-const rvalue-references to temporary objects. ;-)
Explanation
class C {};
void foo (C& c) {}
C bar() { return C(); }
//bar() returns a temporary object
//temporary objects cannot be non-const referenced
int main()
{
//foo() wants a mutable reference (i.e. non-const)
foo( bar() ); // => compilation error
}
Three fixes
Change foo declaration
void foo (const C& c) {}
Use another object
int main()
{
C c;
foo( c = bar() );
}
Use C++11 rvalue-reference
void foo(C && c) {}
Moreover
To confirm temporary objects are const, this above source code fails for the same reason:
class C {};
void foo(C& c) {}
int main()
{
foo( C() );
}

Using a const reference to a returned by value value

Look at the following example:
string foo(int i) {
string a;
... Process i to build a ...
return a;
}
void bar(int j) {
const string& b = foo(j);
cout << b;
}
I know RVO and NRVO, but I thought that in order to do that, I need to write bar as the following:
void bar(int j) {
string b = foo(j);
cout << b;
}
Both versions seem to work, and I believe with the same performance.
Is it safe to use the first version (with the const reference)?
Thanks.
Assigning a temporary to a const reference is perfectly valid. The temporary object will live until the reference goes out of scope.
While it does not make sense in your example, this feature is often used for function arguments:
string foo(int i) {
string a;
// ...
return a;
}
void bar(const string& str) {
// ...
}
void buzz() {
// We can safely call bar() with the temporary string returned by foo():
bar(foo(42));
}
It's safe in this simple case. It's easy to add code which makes it unsafe, however, and it's confusing to anyone who knows C++: why do you need a reference here? There's no reason to do so, and such code should generally be avoided.
A const-reference is allowed to bind to a temporary, and the live-time of the temporary will be extended to the live-time of the const-reference. So yes, it is safe to use.
Is it safe to use the first version (with the const reference)?
Yes. Binding a temporary to a const reference lengthens the lifetime of the temporary to the lifetime of the reference itself, which is the scope in which the reference is declared:
void f()
{
const string& a = foo(10);
//some work with a
{
const string& b = foo(20);
//some work with b
} //<----- b gets destroyed here, so the temporary also gets destroyed!
//some more work with a
} //<----- a gets destroyed here, so the temporary associated
//with it also gets destroyed!
Herb Sutter has explained this in great detail in his article:
A Candidate For the “Most Important const”
It is worth reading. Must read it.

Which are the implications of return a value as constant, reference and constant reference in C++?

I'm learning C++ and I'm still confused about this. What are the implications of return a value as constant, reference and constant reference in C++ ? For example:
const int exampleOne();
int& exampleTwo();
const int& exampleThree();
Here's the lowdown on all your cases:
• Return by reference: The function call can be used as the left hand side of an assignment. e.g. using operator overloading, if you have operator[] overloaded, you can say something like
a[i] = 7;
(when returning by reference you need to ensure that the object you return is available after the return: you should not return a reference to a local or a temporary)
• Return as constant value: Prevents the function from being used on the left side of an assignment expression. Consider the overloaded operator+. One could write something like:
a + b = c; // This isn't right
Having the return type of operator+ as "const SomeType" allows the return by value and at the same time prevents the expression from being used on the left side of an assignment.
Return as constant value also allows one to prevent typos like these:
if (someFunction() = 2)
when you meant
if (someFunction() == 2)
If someFunction() is declared as
const int someFunction()
then the if() typo above would be caught by the compiler.
• Return as constant reference: This function call cannot appear on the left hand side of an assignment, and you want to avoid making a copy (returning by value). E.g. let's say we have a class Student and we'd like to provide an accessor id() to get the ID of the student:
class Student
{
std::string id_;
public:
const std::string& id() const;
};
const std::string& Student::id()
{
return id_;
}
Consider the id() accessor. This should be declared const to guarantee that the id() member function will not modify the state of the object. Now, consider the return type. If the return type were string& then one could write something like:
Student s;
s.id() = "newId";
which isn't what we want.
We could have returned by value, but in this case returning by reference is more efficient. Making the return type a const string& additionally prevents the id from being modified.
The basic thing to understand is that returning by value will create a new copy of your object. Returning by reference will return a reference to an existing object. NOTE: Just like pointers, you CAN have dangling references. So, don't create an object in a function and return a reference to the object -- it will be destroyed when the function returns, and it will return a dangling reference.
Return by value:
When you have POD (Plain Old Data)
When you want to return a copy of an object
Return by reference:
When you have a performance reason to avoid a copy of the object you are returning, and you understand the lifetime of the object
When you must return a particular instance of an object, and you understand the lifetime of the object
Const / Constant references help you enforce the contracts of your code, and help your users' compilers find usage errors. They do not affect performance.
Returning a constant value isn't a very common idiom, since you're returning a new thing anyway that only the caller can have, so it's not common to have a case where they can't modify it. In your example, you don't know what they're going to do with it, so why should you stop them from modifying it?
Note that in C++ if you don't say that something is a reference or pointer, it's a value so you'll create a new copy of it rather than modifying the original object. This might not be totally obvious if you're coming from other languages that use references by default.
Returning a reference or const reference means that it's actually another object elsewhere, so any modifications to it will affect that other object. A common idiom there might be exposing a private member of a class.
const means that whatever it is can't be modified, so if you return a const reference you can't call any non-const methods on it or modify any data members.
Return by reference.
You can return a reference to some value, such as a class member. That way, you don't create copies. However, you shouldn't return references to values in a stack, as that results in undefined behaviour.
#include <iostream>
using namespace std;
class A{
private: int a;
public:
A(int num):a(num){}
//a to the power of 4.
int& operate(){
this->a*=this->a;
this->a*=this->a;
return this->a;
}
//return constant copy of a.
const int constA(){return this->a;}
//return copy of a.
int getA(){return this->a;}
};
int main(){
A obj(3);
cout <<"a "<<obj.getA()<<endl;
int& b=obj.operate(); //obj.operate() returns a reference!
cout<<"a^4 "<<obj.getA()<<endl;
b++;
cout<<"modified by b: "<<obj.getA()<<endl;
return 0;
}
b and obj.a "point" to the same value, so modifying b modifies the value of obj.a.
$./a.out
a 3
a^4 81
modified by b: 82
Return a const value.
On the other hand, returning a const value indicates that said value cannot be modified. It should be remarked that the returned value is a copy.:
For example,
constA()++;
would result in a compilation error, since the copy returned by constA() is constant. But this is just a copy, it doesn't imply that A::a is constant.
Return a const reference.
This is similiar to returning a const value, except that no copy is return, but a reference to the actual member. However, it cant be modified.
const int& refA(){return this->a;}
const int& b = obj.refA();
b++;
will result in a compilation error.
const int exampleOne();
Returns a const copy of some int. That is, you create a new int which may not be modified. This isn't really useful in most cases because you're creating a copy anyway, so you typically don't care if it gets modified. So why not just return a regular int?
It may make a difference for more complex types, where modifying them may have undesirable sideeffects though. (Conceptually, let's say a function returns an object representing a file handle. If that handle is const, the file is read-only, otherwise it can be modified. Then in some cases it makes sense for a function to return a const value. But in general, returning a const value is uncommon.
int& exampleTwo();
This one returns a reference to an int. This does not affect the lifetime of that value though, so this can lead to undefined behavior in a case such as this:
int& exampleTwo() {
int x = 42;
return x;
}
we're returning a reference to a value that no longer exists. The compiler may warn you about this, but it'll probably compile anyway. But it's meaningless and will cause funky crashes sooner or later. This is used often in other cases though. If the function had been a class member, it could return a reference to a member variable, whose lifetime would last until the object goes out of scope, which means function return value is still valid when the function returns.
const int& exampleThree();
Is mostly the same as above, returning a reference to some value without taking ownership of it or affecting its lifetime. The main difference is that now you're returning a reference to a const (immutable) object. Unlike the first case, this is more often useful, since we're no longer dealing with a copy that no one else knows about, and so modifications may be visible to other parts of the code. (you may have an object that's non-const where it's defined, and a function that allows other parts of the code to get access to it as const, by returning a const reference to it.
Your first case:
const int exampleOne();
With simple types like int, this is almost never what you want, because the const is pointless. Return by value implies a copy, and you can assign to a non-const object freely:
int a = exampleOne(); // perfectly valid.
When I see this, it's usually because whoever wrote the code was trying to be const-correct, which is laudable, but didn't quite understand the implications of what they were writing. However, there are cases with overloaded operators and custom types where it can make a difference.
Some compilers (newer GCCs, Metrowerks, etc) warn on behavior like this with simple types, so it should be avoided.
I think that your question is actually two questions:
What are the implications of returning a const.
What are the implications of returning a reference.
To give you a better answer, I will explain a little more about both concepts.
Regarding the const keyword
The const keyword means that the object cannot be modified through that variable, for instance:
MyObject *o1 = new MyObject;
const MyObject *o2 = o1;
o1->set(...); // Will work and will change the instance variables.
o2->set(...); // Won't compile.
Now, the const keyword can be used in three different contexts:
Assuring the caller of a method that you won't modify the object
For example:
void func(const MyObject &o);
void func(const MyObject *o);
In both cases, any modification made to the object will remain outside the function scope, that's why using the keyword const I assure the caller that I won't be modifying it's instance variables.
Assuring the compiler that a specific method do not mutate the object
If you have a class and some methods that "gets" or "obtains" information from the instance variables without modifying them, then I should be able to use them even if the const keyword is used. For example:
class MyObject
{
...
public:
void setValue(int);
int getValue() const; // The const at the end is the key
};
void funct(const MyObject &o)
{
int val = o.getValue(); // Will compile.
a.setValue(val); // Won't compile.
}
Finally, (your case) returning a const value
This means that the returned object cannot be modified or mutated directly. For example:
const MyObject func();
void func2()
{
int val = func()->getValue(); // Will compile.
func()->setValue(val); // Won't compile.
MyObject o1 = func(); // Won't compile.
MyObject o2 = const_cast<MyObject>(func()); // Will compile.
}
More information about the const keyword: C++ Faq Lite - Const Correctness
Regarding references
Returning or receiving a reference means that the object will not be duplicated. This means that any change made to the value itself will be reflected outside the function scope. For example:
void swap(int &x, int &y)
{
int z = x;
x = y;
y = z;
}
int a = 2; b = 3;
swap(a, b); // a IS THE SAME AS x inside the swap function
So, returning a reference value means that the value can be changed, for instance:
class Foo
{
public:
...
int &val() { return m_val; }
private:
int m_val;
};
Foo f;
f.val() = 4; // Will change m_val.
More information about references: C++ Faq Lite - Reference and value semantics
Now, answering your questions
const int exampleOne();
Means the object returned cannot change through the variable. It's more useful when returning objects.
int& exampleTwo();
Means the object returned is the same as the one inside the function and any change made to that object will be reflected inside the function.
const int& exampleThree();
Means the object returned is the same as the one inside the function and cannot be modified through that variable.
Never thought, that we can return a const value by reference and I don't see the value in doing so..
But, it makes sense if you try to pass a value to a function like this
void func(const int& a);
This has the advantage of telling the compiler to not make a copy of the variable a in memory (which is done when you pass an argument by value and not by reference). The const is here in order to avoid the variable a to be modified.