|
![](/i/fill.gif) |
On 3/5/2012 11:13 AM, nemesis wrote:
> BTW, why
>
> Array(std::size_t size):
> mData(new Value_t[size]),
> mSize(size)
> {}
>
> rather than
>
> Array(std::size_t size)
> {
> mData=new Value_t[size];
> mSize=size;
> }
>
> when you've got exactly 2 extra chars (:,) in the first case? Don't tell
> me it's because some compile-time initialization that is not done in the
> second case...
It's because the second case doesn't initialize the variables, but
rather assigns to them. This distinction matters in C++, and in general
here's how the code plays out in the two cases when you instantiate the
class:
case 1:
1 - call mData constructor with parameter `new Value_t[size]'
2 - call mSize constructor with parameter `size'
case2:
1 - call no-parameter mData constructor
2 - call no-parameter mSize constructor
3 - call mData assignment operator with parameter `new Value_t[size]'
4 - call mSize assignment operator with parameter `size'
In this particular case I think the code generated by most compilers
would be identical, but the former is better practice since in other
situations the generated code will be different. There's also cases
where the second case won't even compile, for instance if one of the
member fields lacks a zero-parameter constructor.
> is also delete[] defined when you define those operator[] methods?
delete[] is built in to the language and frees the memory associated
with a call to an array allocation performed with new[].
> C++ is so alien...
Depends on what languages you feel at home in, obviously.
Post a reply to this message
|
![](/i/fill.gif) |