Sep 11, 2009 at 3:30pm Sep 11, 2009 at 3:30pm UTC
Line 3 in the second snippet doesn't declare an object named tmp of type B. It declares a function named tmp that takes no parameters and returns a B.
Sep 11, 2009 at 3:57pm Sep 11, 2009 at 3:57pm UTC
For jsmith:
Thanks for the suggestions.
Unfortunately Obj1 and Obj2 are not copiable, using std::swap I get:
error C2582: 'operator =' function is unavailable in 'Obj1' (VS2008)
I don't understand why before I can compile the code! Why I cannot use the default copy?
For helios:
You're right! It's my typing error! :-)
Thanks to both!
Daniele.
Sep 11, 2009 at 4:17pm Sep 11, 2009 at 4:17pm UTC
To make the assignment operator more efficient, self assignment cases should be tested before the swap:
1 2 3 4 5 6 7 8 9
B& B::operator =( B& b )
{
if ( this != &b)
{
swap( o1, b.o1 );
swap( o2_ptr, b.o2_ptr );
}
return *this ;
}
Last edited on Sep 11, 2009 at 4:19pm Sep 11, 2009 at 4:19pm UTC
Sep 11, 2009 at 4:48pm Sep 11, 2009 at 4:48pm UTC
@Robertlzw:
But your version has the limitation that the rhs of the equal sign cannot be const.
EDIT: And indeed, you actually modify the object on the rhs of the equal sign as well as the left!
@DBarzo:
If Obj1 is not copyable, then B isn't copyable either. If you want to make B copyable/assignable,
then Obj1 has to be copyable/assignable also.
Last edited on Sep 11, 2009 at 4:49pm Sep 11, 2009 at 4:49pm UTC
Sep 11, 2009 at 6:36pm Sep 11, 2009 at 6:36pm UTC
Since the function takes its rhs by value, the if() check will never be true, even if
the programmer does
a = a;
Therefore, self assignment is necessarily expensive. On the other hand, it's kind
of silly to write
a = a;
Last edited on Sep 11, 2009 at 6:37pm Sep 11, 2009 at 6:37pm UTC
Sep 14, 2009 at 7:51am Sep 14, 2009 at 7:51am UTC
Thanks to all for your suggestions.
I changed my implementation.
The problem was on inserting object B into the A std::map with operator[] : Bs[key] = newObjB
I changed the implementation using the insert method:
pair<std::string, B> item(key, newObjB);
Bs.insert(item);
(in this case I don't check the insert return value)
In this manner the B object doesn't need to be copyable.
Cheers,
Daniele.