0

This is likely a simple question. Consider:

class foo
{
  int * p;

  public:
    foo(int i)
    { int t[i]; p = t; }

 };

Is p a dangling pointer once the constructor goes out of scope? Do I have to do it with new[]?

Tia

1 Answers1

3

Is p a dangling pointer once the constructor goes out of scope?

Yes, the lifetime of t ends when you leave the constructor. Also, variable length arrays like t[i] are a gcc/clang extension and not part of standard C++.

Do I have to do it with new[]?

No! You should use the much easier and better std::vector instead!

class foo {
  std::vector<int> p;

  public:
    foo(int i) : p(i) {}        
};

You can access its elements with p[k] just as you would with a C-style array, but do not need to worry about that nasty memory management.

See here for a full documentation of what you can do with std::vector.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182