samedi 22 avril 2017

Why this reference doesn't work?

I have this file:

A.h

struct B;

struct A
{
    A(... const B &b) :
        b(std::cref(b)) {}

    std::reference_wrapper<B const> &b;
};

And B.h:

#include "A.h"
struct B{
...
std::vector<A> as;
}

And I have this code:

vector<B> localB;
for(int i=0; i<n; i++)
  for(int j=2; j<m; j++)
    localWrapper.push_back(B(...));

int c=0;
std::vector<A> manya;
for(int i=0; i<n; i++)
  for(int j=2; j<m; j++){
    ...
    for(int z=0; z<k; z++){
      A a(...,localB[c]);
      localB[c].as.push_back(a);
    }
    manya.insert(manya.end(), localB[c].begin(), localB[c].end());
    c++;
  }

//use manya

The code above works as expected

However, this code doesn't work:

vector<B> localB;

int c=0;
std::vector<A> manya;
for(int i=0; i<n; i++)
  for(int j=2; j<m; j++){
    localWrapper.push_back(B(...));
    ...
    for(int z=0; z<k; z++){
      A a(...,localB.back());
      localB.back().as.push_back(a);
    }
    manya.insert(manya.end(), localB.back(), localB.back());
  }

In particular, it seems that the reference manya[].b seems to be invalid. I really simplified the code that is actually use, I hope that the problem is still valid.

Aucun commentaire:

Enregistrer un commentaire