Jump to content

  • Log In with Google      Sign In   
  • Create Account

FREE SOFTWARE GIVEAWAY

We have 4 x Pro Licences (valued at $59 each) for 2d modular animation software Spriter to give away in this Thursday's GDNet Direct email newsletter.


Read more in this forum topic or make sure you're signed up (from the right-hand sidebar on the homepage) and read Thursday's newsletter to get in the running!


Unexpected program flow (templates / conversion operator).


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

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

#1 tanzanite7   Members   -  Reputation: 1378

Like
0Likes
Like

Posted 15 January 2013 - 12:52 PM

Experiencing unexpected program flow.
 
Minimal testcase follows:
class Obj {
public:
    Obj() { LOG(L"new Obj"); }
    ~Obj() { LOG(L"del Obj"); }
};

template<class T, template<class> class W> class Emit {
public:
    Emit(T* ref) : m_ref(ref) { LOG(L"new Emit"); }
    W<T> get() { LOG(L"get from Emit"); return W<T>(m_ref); }
    T* m_ref;
};

template<class T> class Wrap {
public:
    Wrap() : m_ref(0) { LOG(L"new Wrap(0)"); }
    Wrap(T* ref) : m_ref(ref) { LOG(L"new Wrap(T*)"); }
    Wrap(Wrap<T>& ref) : m_ref(&ref) { LOG(L"new Wrap(Wrap<T>&)"); ref.m_ref = 0; }
    ~Wrap() { LOG(L"del Wrap : %p",m_ref); }

    operator T*() const { LOG(L"Wrap to T*"); return m_ref; }

    Wrap<T>& operator=(T* ref) { LOG(L"Wrap = T*"); m_ref = ref; return *this; } // this will be used, incorrectly, when i use assignment instead
    Wrap<T>& operator=(Wrap<T>& ref) { LOG(L"Wrap = Wrap<T>&"); m_ref = ref.m_ref; ref.m_ref = 0; return *this; }

    T* m_ref;
};

void wtf() {
    Emit<Obj, Wrap> emit(new Obj());
    Wrap<Obj> wrap = emit.get();
}

expecting:
new Obj
new Emit
get from Emit
new Wrap(T*)        - first formed in Emit::get
new Wrap(Wrap<T>&)  - copy constructor (return value optimization removes the second one)
del Wrap : 00000000 - delete temporary object ... content has been transferred
del Wrap : 006F6580 - "wrap" goes out of scope

but actually get:
new Obj
new Emit
get from Emit
new Wrap(T*)        - first formed in Emit::get
Wrap to T*          - have to downcast/unwrap to use the wrong copy constructor
new Wrap(T*)        - using the wrong copy constructor
del Wrap : 006F6580 - delete temporary object ... this is bananas
Wrap to T*               ???
new Wrap(T*)             ??? going bananas twice, presumably first at "Wrap<Obj> get() { return Wrap<Obj>(ref); }" and then "Wrap<Obj> = emit.get();"
del Wrap : 006F6580      ??? given that it goes bananas - no return value optimization is done with Debug nor Release target.
del Wrap : 006F6580 - "wrap" goes out of scope

What am i missing? Can i force it to be sensible?

Sponsor:

#2 EWClay   Members   -  Reputation: 659

Like
1Likes
Like

Posted 15 January 2013 - 01:42 PM

Make Wrap(T* ref) explicit.

 

Otherwise the compiler will prefer it over a non-const copy constructor.



#3 tanzanite7   Members   -  Reputation: 1378

Like
0Likes
Like

Posted 15 January 2013 - 02:05 PM

Did not think of "explicit" - nice. Now return value optimization is in action and actually removes even more than i hoped for smile.png.
new Obj
new Emit
get from Emit
new Wrap(T*)
del Wrap : 00556580
However, one problem remains - assignment still goes to places:
new Obj
new Emit
new Wrap(0)
get from Emit
new Wrap(T*)
Wrap to T*      - bananas
Wrap = T*
del Wrap : 005565C0
del Wrap : 005565C0
Is there something i could do to make it prefer the templated one?

edit: FFS, gamedev, fix the god-damn forum software - i have been around here ~10 years and i can not remember any time any of the forum software variations have ever worked fully. It is not even funny anymore.

#4 Brother Bob   Moderators   -  Reputation: 8630

Like
3Likes
Like

Posted 15 January 2013 - 02:16 PM

You probably want the copy constructor and the assignment operator to take the parameter by const reference instead of by reference. For example, the return statement is Obj::get() takes an unexepected route because it cannot copy by the copy constructur; it would pass a temporary value to a function taking a non-const reference which is not legal.

 

The same problem applies to the assignment operator; the return value from Obj::get() is a temporary and cannot be passed to the assignment operator taking a non-const reference. But your assignment operator is behaving in an unexpected way anyway; it modifies the right-hand-side (sets ref.m_ref to zero) which is not the expected behavior of a copy-assignment. What you have implemented is the move-assignment operator disguised as the copy-assignment operator.



#5 Cornstalks   Crossbones+   -  Reputation: 6991

Like
1Likes
Like

Posted 15 January 2013 - 03:04 PM

Can't upvote Brother Bob's post enough.

 

For example, the return statement is Obj::get() takes an unexepected route because it cannot copy by the copy constructur; it would pass a temporary value to a function taking a non-const reference which is not legal.

To expand on this a little bit:

// Invalid example:
void foo(int& x)
{
    std::cout << x << std::endl;
}
 
foo(7 * 6); // not legal; can't bind a temporary to a non-const reference (because what if foo() changed it?)
 
// Valid example
void foo(const int& x)
{
    std::cout << x << std::endl;
}
 
foo(7 * 6); // legal; the temporary is bound to a const reference, so the compiler doesn't have to worry about foo() modifying it

 

Invalid example and Valid example.


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#6 tanzanite7   Members   -  Reputation: 1378

Like
0Likes
Like

Posted 15 January 2013 - 03:08 PM

1) You probably want the copy constructor and the assignment operator to take the parameter by const reference instead of by reference. For example, the return statement is Emit::get() takes an unexepected route because it cannot copy by the copy constructur; it would pass a temporary value to a function taking a non-const reference which is not legal.
 
2) The same problem applies to the assignment operator; the return value from Obj::get() is a temporary and cannot be passed to the assignment operator taking a non-const reference.

3) But your assignment operator is behaving in an unexpected way anyway; it modifies the right-hand-side (sets ref.m_ref to zero) which is not the expected behavior of a copy-assignment. What you have implemented is the move-assignment operator disguised as the copy-assignment operator.
Maybe it is getting late or i have language barrier problems, but i do not understand what was said. :/

1) I assume by "const reference" (makes no sense to me and pretty sure VC wont even allow it) you mean actually "reference to const" in which case - no, in my case. Source cannot be const (look it like a tape from old days - the copy is not a perfect clone and the source suffered some wear and is not what it used to be either).

"it would pass a temporary value to a function taking a non-const reference to non-const which is not legal" - why? Can you give some example of what you mean?

2) Why not? (assuming reference to non-const was meant)

3) Unusual, perhaps, but perfectly reasonable. It is not copy-assignment nor move-assignment (it only looks like move assignment because it is a minimized example-case) - it is just an assignment that does stuff that is expected to happen when one uses assignment with the relevant object types.

#7 tanzanite7   Members   -  Reputation: 1378

Like
0Likes
Like

Posted 15 January 2013 - 03:18 PM

@Cornstalks: thanks for the example (why do you refer to "reference to non-const" as "non-const reference"?) - trying to understand it now.

#8 Bregma   Crossbones+   -  Reputation: 5494

Like
0Likes
Like

Posted 15 January 2013 - 03:27 PM

3) Unusual, perhaps, but perfectly reasonable. It is not copy-assignment nor move-assignment (it only looks like move assignment because it is a minimized example-case) - it is just an assignment that does stuff that is expected to happen when one uses assignment with the relevant object types.

 

 

If you try to force the language to do the unexpected, like having something that looks like like it might be an assignment operator not have the signature of an assignment operator and not work like an assignment operator, you should really expect your program to do the unexpected.

 

Also, there is a significant difference between a const reference and a reference to a const.  One is "int const&" the other is "int& const"...  can you guess which is which, and which one "const int&" is?


Stephen M. Webb
Professional Free Software Developer

#9 Cornstalks   Crossbones+   -  Reputation: 6991

Like
1Likes
Like

Posted 15 January 2013 - 03:53 PM

@Cornstalks: thanks for the example (why do you refer to "reference to non-const" as "non-const reference"?) - trying to understand it now.

Because that's how the rest of the world typically does it (at least in English). I guess you could technically call it a misnomer, maybe, but references themselves are always const (so it makes no sense to have a truly "non-const reference" (that is, a reference that can be changed to refer to another object; it's impossible in C++)), so when people talk about (non) const references, the (non) const always refers to the object that the reference refers to, not to the reference itself (since the reference itself is always const).


Edited by Cornstalks, 15 January 2013 - 04:07 PM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#10 EWClay   Members   -  Reputation: 659

Like
0Likes
Like

Posted 15 January 2013 - 04:09 PM

You could drop the = T* operator and allow assignment only from another Wrap<T>.

But yes, this type of thing can make code behave in unexpected ways. Even std::auto_ptr is deprecated for that reason.

#11 tanzanite7   Members   -  Reputation: 1378

Like
0Likes
Like

Posted 15 January 2013 - 04:45 PM

"foo(7*6)" with reference to non-const "foo" function gives in VC: "initial value of reference to non-const must be an lvalue" - perfectly reasonable. Did not realize compiler is willing to create a new temporary constant object in this case - thanks, me likes.

However. My actual Emit::get() code is like:
Wrap<T> get() {
    Wrap<T> result;
    ... more stuff
    return result;
}
The internal copy of "result" may not be destroyed before it is returned - i fail to see the relevance of the given example (call me dense). I do not see any reason why the compiler would care what happens with "result" before it is destroyed - Wrap<T> destructor tells all it needs to know. Ie. it is not a compiler temporary created for referencing purposes - it is local variable which also happens to be returned and hopefully short-circuited by return value optimization.

Also, using "explicit" and forcing it to use the correct copy constructor does get around that problem (plugged into my actual code and it passed all my test cases - as far as i can see it does exactly what i expect it to do). Acceptable workaround (would prefer the constructor not being "explicit" tho).

Assignment, however is much more problematic (no "explicit" keyword to hide the "wrong" one) - if i comment the other one out, and hence force it to use the right one, then it works. Cannot make the type conversion explicit either sad.png (that would fix all the problem without needing any workarounds, unfortunately - not an acceptable loss).

Irritating. Prefers a function it can only use through implicit type conversion to the function that matches from start :/.

3) Unusual, perhaps, but perfectly reasonable. It is not copy-assignment nor move-assignment (it only looks like move assignment because it is a minimized example-case) - it is just an assignment that does stuff that is expected to happen when one uses assignment with the relevant object types.


1) If you try to force the language to do the unexpected, like having something that looks like like it might be an assignment operator not have the signature of an assignment operator and not work like an assignment operator, you should really expect your program to do the unexpected.

2) Also, there is a significant difference between a const reference and a reference to a const. One is "int const&" the other is "int& const"... can you guess which is which, and which one "const int&" is?


1) Unexpected != unusual. One would fully expect that particular class to behave exactly the way it does. What the hell are you blabbering about?
2) You did not pay any attention to what i have said, right? I know perfectly well what is what - i had problems digesting a response where parts of it made no sense.

why do you refer to "reference to non-const" as "non-const reference"?

Because that's how the rest of the world typically does it (at least in English). I guess you could technically call it a misnomer, maybe, but references themselves are always const (so it makes no sense to have a truly "non-const reference" (that is, a reference that can be changed to refer to another object; it's impossible in C++)), so when people talk about (non) const references, the (non) const always refers to the object that the reference refers to, not to the reference itself (since the reference itself is always const).


Thanks for the explanation. Is it something that is accepted in English CS classes? Correct terminology was quite important for us - unfortunately, none of it was in English, so i tend to be cautiously confused when i encounter something in English that does not seem to make any sense.

I recommend you and everyone else drop the incorrect usage - impossibility of "non-const reference" is an unacceptable reason to refrain using the perfectly valid "reference to const". VC agrees with me and also uses "reference to const" ;).

Sorry if i am too picky here.

edit: un-fuckup the forum formatting.

#12 tanzanite7   Members   -  Reputation: 1378

Like
0Likes
Like

Posted 15 January 2013 - 04:54 PM

You could drop the = T* operator and allow assignment only from another Wrap<T>.

But yes, this type of thing can make code behave in unexpected ways. Even std::auto_ptr is deprecated for that reason.
Yeah, dropped the =(T*) operator using a separate function instead in my testbed - probably the way to go (have not yet plugged into main app). Will investigate further tomorrow (evaluate how much of a hassle it will be in real case).

#13 Cornstalks   Crossbones+   -  Reputation: 6991

Like
0Likes
Like

Posted 15 January 2013 - 05:01 PM

 

why do you refer to "reference to non-const" as "non-const reference"?

Because that's how the rest of the world typically does it (at least in English). I guess you could technically call it a misnomer, maybe, but references themselves are always const (so it makes no sense to have a truly "non-const reference" (that is, a reference that can be changed to refer to another object; it's impossible in C++)), so when people talk about (non) const references, the (non) const always refers to the object that the reference refers to, not to the reference itself (since the reference itself is always const).
Thanks for the explanation. Is it something that is accepted in English CS classes? Correct terminology was quite important for us - unfortunately, none of it was in English, so i tend to be cautiously confused when i encounter something in English that does not seem to make any sense.

It's common practice to word it like that in English, yes, both in the professional workplace and in academic universities. English is, in my opinion, a pretty bad language overall and there are tons of times where what we say isn't what we really mean :) I agree that "reference to (non) const" is more technically correct (and is typically used in formal, technical settings), but "(non) const reference" is so common it's not going to go away any time soon. People tend to use it more because it's shorter (and we're lazy in English, unfortunately).


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#14 tanzanite7   Members   -  Reputation: 1378

Like
0Likes
Like

Posted 15 January 2013 - 05:05 PM

As the forum edit function most likely screws up the whole post - i reply to myself instead.
I recommend you and everyone else drop the incorrect usage - impossibility of "non-const reference" is an unacceptable reason to refrain using the perfectly valid "reference to const". VC agrees with me and also uses "reference to const" ;).
Ugh, as one of our teachers used to say: "the mouth is singing and the hearth worrying" - that really should be "reference to non-const".

#15 SiCrane   Moderators   -  Reputation: 9674

Like
2Likes
Like

Posted 15 January 2013 - 06:05 PM

Given that the C++ Standard uses the terms "const reference" and "non-const reference" it seems that they are, in fact, correct terms. E.g. section 5.2.2 paragraph 5 of ISO/IEC 14882:1998 has the line "Where a parameter is of const reference type a temporary object is introduced if needed...."

#16 Cornstalks   Crossbones+   -  Reputation: 6991

Like
0Likes
Like

Posted 15 January 2013 - 06:10 PM

Given that the C++ Standard uses the terms "const reference" and "non-const reference" it seems that they are, in fact, correct terms. E.g. section 5.2.2 paragraph 5 of ISO/IEC 14882:1998 has the line "Where a parameter is of const reference type a temporary object is introduced if needed...."

Sweet, I was wondering if it did (and was too lazy to dig through it to see)


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS