Rewriting in C++11

This forum can be used to talk about general design strategies, new ideas and questions in general related to wxWidgets. If you feel your questions doesn't fit anywhere, put it here.
Post Reply
ONEEYEMAN
Part Of The Furniture
Part Of The Furniture
Posts: 7459
Joined: Sat Apr 16, 2005 7:22 am
Location: USA, Ukraine

Rewriting in C++11

Post by ONEEYEMAN »

Hi, ALL,

I am trying to rewrite a following code:

Code: Select all

wchar_t **p;
for( int i = 0; i < num; i++ )
{
    p = new int*[i];
}
for( int i = 0; i < num; i++ )
{
    p[i] = new wchat_t[256];
}
to be something like this:

Code: Select all

auto p = std::unique_ptr<wchar_t[num]>{ new wchar_t( 256 ) };
but this code gave me errors:
error C2540: non-constant expression as array bound
error C2440: 'initializing': cannot convert from 'initializer list' to 'std::unique_ptr<wchar_t [1],std::default_delete<_Ty>>'
So, what am I doing wrong? How do I fix those errors?

Thank you.
klas.marcks
Knows some wx things
Knows some wx things
Posts: 42
Joined: Thu Mar 13, 2014 9:49 pm

Re: Rewriting in C++11

Post by klas.marcks »

Assuming you are trying to do

Code: Select all

constexpr int num = 10;
wchar_t **p;

p = new wchar_t*[num];
for( int i = 0; i < num; i++ )
{
    p[i] = new wchar_t[256];
}
I think the appropriate way would be

Code: Select all

auto p = std::unique_ptr<wchar_t[][256]>(new wchar_t[num][256]());
but I might have missinterpreted your intention since your original example seems odd (Or I'm just not clever enough... )

regards
Klas
ONEEYEMAN
Part Of The Furniture
Part Of The Furniture
Posts: 7459
Joined: Sat Apr 16, 2005 7:22 am
Location: USA, Ukraine

Re: Rewriting in C++11

Post by ONEEYEMAN »

Hi,
You presumption is correct.
However it is not known at compile time what the value of the num is....

Thank you.
klas.marcks
Knows some wx things
Knows some wx things
Posts: 42
Joined: Thu Mar 13, 2014 9:49 pm

Re: Rewriting in C++11

Post by klas.marcks »

Ok,

How about

Code: Select all

size_t num = 5;

//Take care! Do we need to define our own delete function? I'm unsure.
auto delete_lambda = [](wchar_t* f) { delete[] f; f=nullptr;};

std::vector<std::unique_ptr<wchar_t[], decltype(delete_lambda)>> p;
p.reserve(num);
for (size_t i = 0; i < num; ++i)
{
    p.push_back(std::unique_ptr<wchar_t[], decltype(delete_lambda)>(new wchar_t[256](), delete_lambda));
}

//Access
p[4][56] = L'e';
regards
-Klas
PB
Part Of The Furniture
Part Of The Furniture
Posts: 4193
Joined: Sun Jan 03, 2010 5:45 pm

Re: Rewriting in C++11

Post by PB »

Perhaps the lambda deleter can be avoided and std::default_delete used instead? https://stackoverflow.com/questions/436 ... -with-char

However, I would say that you provided too little information about the indented usage. For cases where the array is constructed at once and treated as a read-only, good old vector<wstring> or vector<array<wchar_t, 256>> may be good enough.
Post Reply