-1

I am trying to improve my skills in C++.Suppose that i have the following piece of code

#include <iostream>

using namespace std;

int main()
{
    int *p;
    p=new int[10];
    delete [] p;
    return 0;
}

How can i use unique/shared ptr to automatically delete the array instead of doing it manually when it goes out of scope in this piece of code?BTW i have read in SO that i might need to download boost library to use a unique/shared ptr.Can anyone confirm this?Or is it included in std libraries?

John M.
  • 245
  • 1
  • 3
  • 13
  • You are going to need some [good resources](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Please head over there now. – WhiZTiM May 09 '17 at 20:40
  • 1
    @WhiZTiM Thanks,in fact i have the book Programming: Principles and Practice Using C++ which was written by Bjarne Stroupstrup and it is a really good book,but it is quite hard to understand after some chapters. – John M. May 09 '17 at 20:42

2 Answers2

4

There is std::unique_ptr<T[]> in C++11, which allows you to do this:

std::unique_ptr<int[]> p(new int[10]);

If you want a compile-time constant array, you can use std::array instead:

std::array<int, 10> p;

Otherwise, just pick the good old std::vector instead:

std::vector<int> p(10);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • "*But `unique_ptr` is not suited for arrays and you shouldn't use it for them*" - that statement is misleading. `std::unique_ptr` is *specifically designed* for arrays (it even exposes an `operator[]` for indexing). It works just fine. – Remy Lebeau May 09 '17 at 20:46
  • @RemyLebeau Fair enough, thanks for the edit too, what I meant was that it's unusual. – Hatted Rooster May 09 '17 at 20:46
3

Since C++11, std::unique_ptr is included in the Standard Library. You can do:

#include <memory>

int main()
{
    std::unique_ptr<int[]> p( new int[10] );
}

By the way, using namespace std; is a bad habit to get into.

You might also consider using std::vector<int> instead of std::unique_ptr<int[]>.

Community
  • 1
  • 1
aschepler
  • 70,891
  • 9
  • 107
  • 161
  • Is it bad using namespace std in general or only in header files?I always use using namespace std only in .cpp files and never in .h. – John M. May 09 '17 at 20:47
  • 1
    @JohnM. it is bad in general. – Remy Lebeau May 09 '17 at 20:48
  • @JohnM. It's slightly *less bad* to use it in .cpp files than it is to use it in .h files, but it's still bad. The ideal is self-documenting code, whereby it's easy for anyone reading the code to immediately know what's going on, and where your types are derived from, and `using namespace std;` harms that, regardless of whether you're polluting namespaces with it (in .h files) or not (in .cpp files). – Xirema May 09 '17 at 20:50