question about return temp object.

1
2
3
4
5
6
7
hello operator=(const hello& n){
    hello temp;
    return temp;
}
hello operator=(const hello& n){
    return hello();
}


why the second version isn't same with the first one.

ps. plz ignore the logic problem why return temp in an operator= method.
Last edited on
hello(); is a function. Your returning the default constructor. What type does a default constructor have? Think about it. return temp; is returning an object
Last edited on
Thx for reply.


But I found an example in the book:
1
2
3
4
5
6
7
8
class f_mod
{
private:
    int dv;
public:
    f_mod(int d = 1) : dv(d) {}
    bool operator()(int x) {return x % dv == 0;}
};

it's a functor used to see whether the argument x can be divided by dv.

and apply it in one vector<int> object which has 1000 members inside:
 
auto count3 = std::count_if(numbers.begin(), numbers.end(), f_mod(3));


the following is from the book:

The argument f_mod(3) creates an object storing the value 3, and count_if() uses the created object to call the operator()() method, setting the parameter x equal to an element of numbers


then why here f_mod(3) means create one object while return hello(); doesn't?
Okay, ignoring all logic as you requested, I think "return hello();" does create an object.

The difference would be more important if you were using references, and you'd have to worry about const vs non-const references, since "return hello();" creates a temporary unnamed object. Of course you shouldn't try and return a reference to a local variable (temp).
Topic archived. No new replies allowed.