operator new and parameterized constructor



 DEVELOP > c-Plus-Plus > operator new and parameterized constructor

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "Daniel Fortin"
Date: 19 Oct 2003 12:57:15 PM
Object: operator new and parameterized constructor
Hi, I was wondering if anyone knows how to overload operator new to
use a parameterized constructor.
Something like this:
class class1
{
public:
class1();
class1(int parameter1);
}
int main()
{
int number=32;
class1 * temp;
temp= new class1[number](parameter1);
}
Thanks
.

User: "Mike Wahler"

Title: Re: operator new and parameterized constructor 19 Oct 2003 01:37:16 PM
"Daniel Fortin" <danielfortin86@hotmail.com> wrote in message
news:d38b5d24.0310190957.7b66e021@posting.google.com...

Hi, I was wondering if anyone knows how to overload operator new to
use a parameterized constructor.

Something like this:

class class1
{
public:
class1();
class1(int parameter1);

}

int main()
{
int number=32;
class1 * temp;
temp= new class1[number](parameter1);
}

I believe the restrictions on overloading operator 'new[]'
do not allow this. But you could write a function to achieve it:
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iterator>
template <typename T, typename PT>
T *initialized_alloc(std::size_t count, PT arg)
{
T *p = new T[count];
std::fill(p, p + count, arg);
return p;
}
class C
{
int mem;
public:
C() {} /* 'new[]' needs a default ctor */
C(int arg) : mem(arg) { } /* ctor with param */
operator int() const { return mem; } /* facilitates 'simple' */
/* output below */
};
int main()
{
std::size_t how_many(10);
C *p = initialized_alloc<C>(how_many, 42);
std::copy(p, p + how_many,
std::ostream_iterator<int>(std::cout, "\n"));
delete[] p;
return 0;
}
But this might be more trouble than it's worth. :-)
-Mike
.
User: "Rolf Magnus"

Title: Re: operator new and parameterized constructor 19 Oct 2003 06:39:40 PM
Mike Wahler wrote:


"Daniel Fortin" <danielfortin86@hotmail.com> wrote in message
news:d38b5d24.0310190957.7b66e021@posting.google.com...

Hi, I was wondering if anyone knows how to overload operator new to
use a parameterized constructor.

Something like this:

class class1
{
public:
class1();
class1(int parameter1);

}

int main()
{
int number=32;
class1 * temp;
temp= new class1[number](parameter1);
}


I believe the restrictions on overloading operator 'new[]'
do not allow this. But you could write a function to achieve it:

Or just use std::vector:
std::vector<class1>(number, class1(parameter1));
However, that does not initialize each element with parameter1, but
rather copy-construct them from the temporary you give as argument.
.



  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER