• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
tanzanite7

Unexpected program flow (templates / conversion operator).

15 posts in this topic

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?
0

Share this post


Link to post
Share on other sites

Make Wrap(T* ref) explicit.

 

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

1

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

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:

[code]// 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[/code]

 

Invalid example and Valid example.

1

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
@Cornstalks: thanks for the example (why do you refer to "reference to non-const" as "non-const reference"?) - trying to understand it now.
0

Share this post


Link to post
Share on other sites
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?

0

Share this post


Link to post
Share on other sites
@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
1

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
"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.
0

Share this post


Link to post
Share on other sites
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).
0

Share this post


Link to post
Share on other sites

 

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).

0

Share this post


Link to post
Share on other sites
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".
0

Share this post


Link to post
Share on other sites
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...."
2

Share this post


Link to post
Share on other sites
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)

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0