4

I'm trying to use the initializer_list to instantiate a class, but got wired error.

When try to create a `ClassB``variable using:

ClassB b = { { 1, {} }, { 2, {} };

A memory access violation will occur. However if change to:

ClassA a0, a1;
ClassB b = { { 1, a0 }, { 2, a1 } };

The error disappears.

I tried compile with VC 2013 (without update 1) and gcc-c++ 4.8.1. Using gcc-c++ 4.8.1 doesn't yield any runtime error. Is it an bug in VC?

Can any one help to confirm? Thanks!

Below is the SSCCE:

#include <iostream>
#include <initializer_list>
#include <map>
#include <vector>
#include <memory>

using namespace std;

struct ClassA {
  struct Data {
    vector<int> vs;
  };
  unique_ptr<Data> d;

  ClassA() : d(new Data()) {}
  ClassA(const ClassA& a) : ClassA() {
    *d = *(a.d);
  }
};

struct ClassB {
  ClassB(initializer_list<pair<const int, ClassA> > v) { as = v; }
  map<int, ClassA> as;
};

int main() {
  ClassA a0, a1;
  // ClassB b = { { 1, a0 }, { 2, a1 } };     // won't crash in VC
  ClassB b = { { 1, {} }, { 2, {} } };
  return 0;
}
Xin
  • 1,300
  • 2
  • 14
  • 27

1 Answers1

-2

The problem is that unique_ptr offers automatic object destruction when the pointer goes out of scope . if you change

  unique_ptr<Data> d;

to

    Data * d;

it would work properly :

    b.as.begin()->second.d->vs.push_back(1);

I'm not suggesting that this is necessarily the (only) solution and the right way out of this problem .

ColonelMo
  • 134
  • 1
  • 9
  • `unique_ptr` is not the problem here. – Danvil May 02 '14 at 08:23
  • So would you please explain why removing it makes the the runtime error go away ? – ColonelMo May 02 '14 at 11:42
  • 1
    By using a plain pointer instead of `unique_ptr` you are using a different technique. This removes the error, however the original technique using `unique_ptr` should work as well. The source of the problem is not `unique_ptr` but a bug in VS2013. – Danvil May 02 '14 at 13:41
  • Agreed , but isn't that what i stated at the end of the post ? I neglect to see the reason for downvotes . – ColonelMo May 03 '14 at 03:52
  • "The problem is that unique_ptr offers automatic object destruction when the pointer goes out of scope ." -- this is *not* the problem. – Danvil May 03 '14 at 08:34