Ampersand after type

Started by
13 comments, last by Skeleton_V@T 18 years, 4 months ago
Quote:Original post by Zahlman
references can be used as l-values, so for example you could do createVector(myTail, myHead).doSomething();.

You can do that with an rvalue too.
Advertisement
You might want to specify const-reference return value. This will ensure no temporary object will be created for efficiency and also protect your member variable from being undesirably mutated.

[Edit:]
inline const cl_3dVector < tType > & createVector(const cl_3dPoint < tType > & tail, const cl_3dPoint < tType > & head)

Well, :-p you've already did it.
--> The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones <--
Quote:Original post by kelaklub
Then would you mind explaining where the unhappiness might arise from?


from the constant void in one's life?
Quote:Original post by Skeleton_V@T
You might want to specify const-reference return value. This will ensure no temporary object will be created for efficiency and also protect your member variable from being undesirably mutated.

[Edit:]
inline const cl_3dVector < tType > & createVector(const cl_3dPoint < tType > & tail, const cl_3dPoint < tType > & head)

Well, :-p you've already did it.


Well, that's not quite the whole story...
Quote:Original post by Zahlman
Well, that's not quite the whole story...

Can you explain this a bit further ?
The most relevant question that I've found is
[18.15] Why does the compiler allow me to change an int after I've pointed at it with a const int*?

And he has pointed out one possible situation:
Causing a const int* to point to an int doesn't const-ify the int.The int can't be changed via the const int*, but if someone else has an int*(note: no const) that points to ("aliases") the same int, then that int* can be used to change the int. For example: 

 void f(const int* p1, int* p2) {   int i = *p1;         // Get the (original) value of *p1   *p2 = 7;             // If p1 == p2, this will also change *p1   int j = *p1;         // Get the (possibly new) value of *p1   if (i != j) {     std::cout << "*p1 changed, but it didn't change via pointer p1!\n";     assert(p1 == p2);  // This is the only way *p1 could be different   } }  int main() {   int x = 5;   f(&x, &x);           // This is perfectly legal (and even moral!)   ... } 

But in the OP's case, a reference to const value is being returned. Unlike the situation above, I can't have two references - one is const, one isn't - refer to the same thing.

const_cast can't do it.
Reference-to-reference or non-const-pointer-takes-address-of-const-reference doesn't work also.
--> The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones <--

This topic is closed to new replies.

Advertisement