Old problem with performance

Michel Fortin michel.fortin at michelf.com
Mon Feb 9 03:42:54 PST 2009


On 2009-02-08 23:43:13 -0500, Weed <resume755 at mail.ru> said:

> Michel Fortin пишет:
>> On 2009-02-08 09:30:08 -0500, Weed <resume755 at mail.ru> said:
>> 
>>> Let's assume, polymorphism is necessary to these objects
>> 
>> Polymorphism doesn't work very well while passing objects by value, even
>> in C++. This is called the slicing problem.
>> <http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c>
>> 
>> 
>> I think D does a good job at avoiding that problem.
>> 
> 
> By performance loss
> :(

No. By forbiding the cases that leads to slicing, like returning a 
polymorphic object by value.

Returning something by-value always cause slicing in C++. Try this C++ code:

	#include <iostream>

	class A {
	public:
		virtual void hello() { std::cout << "hello from A" << std::endl; }
	};
	class B : public A {
	public:
		virtual void hello() { std::cout << "hello from B" << std::endl; }
	};

	A test() {
		B b;
		b.hello(); // prints "hello from B"
		return b;
	}
	int main() {
		test().hello(); // prints "hello from A"
		A a = test();
		a.hello();      // prints "hello from A"
	}

Here, returning B by value "slices" the object, transforming it into a 
A. There is absolutely no polymorphic behaviour when returning by 
value. It's as if virtual functions weren't virtual at all: your B 
object is transformed to a A when it is returned.

To preserve polymorphism, you need to return a pointer or a reference, 
but then test() can't allocate the object on the stack.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list