1
votes
void Create_moneys(shared_ptr<CoinMoney>* &ms){
    int max = getSize(true);
    for(size_t i = 0; i < max; ++i){
        cout << "ms is : " <<typeid(ms[i]).name() << endl;
        ms[i] = make_shared<CoinMoney>();
        ms[i]->c50 = i+1;
        ms[i]->c100 = i+2;
        ms[i]->c500 = i+3;
    }
}

int main(int argc, char* argv[]){
    shared_ptr<CoinMoney> pm1[getSize(true)];
    Create_moneys(pm1); // error
    for(auto p : pm1)
        CoinMoney_Print(*p);
    return 0;
}

I'm getting this error "cannot bind non-const lvalue reference of type ~ to an rvalue of type

How can I fix this?

1
Why does Create_moneys() accept a reference to a pointer? it's not like your are modyfying it... - Frank
"auto& ms" possible but "shared_ptr<CoinMoney>* ms" is impossible i don't understand this - HyeokJin

1 Answers

4
votes

Create_moneys() is a function that takes a mutable reference to a pointer.

What this means is that it's technically possible for the function to modify the pointer itself in a way that gets propagated to the caller.

For example:

int global_x;
void foo(int*& ptr) {
  ptr = &global_x;
}

void bar() {
  int local_x;
  int * local_ptr = &local_x;
  foo(local_ptr);
  //local_ptr now points to global_x!
}

Now, pm1 is an array, and when you call Create_moneys(pm1); the language creates a temporary pointer that points to the start of the array. That temporary value is called a RValue, and RValues are unmodyfiable constants, so you are not allowed to use them as mutable reference arguments.

The fix is simple, since Create_moneys() does not modify the pointer, it has no reason to take its argument by reference, just declare it as Create_moneys(shared_ptr<CoinMoney>* ms) instead.