Jump to content



Explain this set of Code

  • You cannot reply to this topic
22 replies to this topic

#21 kunos   Members   -  Reputation: 173

Like
0Likes
Like

Posted 29 February 2012 - 06:47 AM

View PostTrienco, on 28 February 2012 - 01:22 PM, said:

And thanks to the new standard the discussion is (finally) obsolete. Get a recent enough compiler and use nullptr. No more ambiguity, no more macros.

true.. and the stl made also the code quoted from the book totally archaic and error prone long time ago.
All is needed is a:

vector< Car*> cars;

member in Garage.. and the addCar function would be as simple as cars.push_back( new Car() );

In C++11 a bit uglier but with the plus of automatic deletion:

vector< shared_ptr<Car> > cars;

cars.push_back( make_shared<Car>() );
Stefano Casillo
Lead Programmer
TWITTER: @KunosStefano
AssettoCorsa - netKar PRO - Kunos Simulazioni

Ad:

#22 rip-off   Moderators   -  Reputation: 2482

Like
0Likes
Like

Posted 29 February 2012 - 06:59 AM

Well, if dispensing with the intrusive list we can probably drop the heap allocations altogether:
class Garage
{
public:
	// ...
	void addCar()
	{
		cars.push_back(Car());
		// alternatively, in C++11, this creates a car inside the vector (rather than copying one in)
		cars.emplace_back();
	}

private:
	std::vector<Car> cars;
}


#23 SiCrane   Moderators   -  Reputation: 2383

Like
1Likes
Like

Posted 29 February 2012 - 07:54 AM

View Postrip-off, on 29 February 2012 - 05:24 AM, said:

I've always wondered whether there was a practical application for the flexibility of this rule, beyond the literal 0 value...
This is the explanation I've heard: programmers frequently misuse the NULL macro, such as assigning it to integers. Sometimes some issues can be detected by using a null pointer constant other than 0. For example, if pointers are 64-bit and ints are 32-bit, assigning 0 to an int won't give you warning that an int doesn't have enough bits to represent an actual full pointer. On the other hand, if long long could hold that value you can #define NULL ((long long)0) which would still be a legal null pointer constant but would also tell you that your destination size is too small if you tried assigning to a regular int.






We are working on generating results for this topic
PARTNERS