• 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
swiftcoder

C++ trivia

10 posts in this topic

Everyone knows that taking a reference to a temporary is a bad idea:
int getX() {
    return 5;
}

int &x = getX();
But how about a const reference?
int getY() {
    return 10;
}

const int &y = getY();
It turns out that unlike the first case, storing a const reference to a temporary actually extends the lifetime of the temporary to lifetime of the const reference (read Herb Sutter on the topic).
 
Entertainingly enough, I learned this piece of C++ trivia when Coverity's static analysis tool tried to tell me that returning a const reference to a temporary was illegal. All I can say is yay for code checking tools that don't understand the C++ standard... Edited by swiftcoder
0

Share this post


Link to post
Share on other sites

y in getY() isn't a temporary. Returning a const reference to it won't extend it's lifetime.

You are entirely right. I wasn't thinking when I wrote up that example.

0

Share this post


Link to post
Share on other sites

Entertainingly enough, I learned this piece of C++ trivia when Coverity's static analysis tool tried to tell me that returning a const reference to a temporary was illegal. All I can say is yay for code checking tools that don't understand the C++ standard...

Incidentally, I'm inclined to side with Coverity here. I can't say for certain unless I saw the code it was actually complaining about, but the standard specifically states that a temporary bound to the returned value in a function only persists until the function exits (12.2 paragraph 5 of C++98 and C++11, though C++11 makes the wording much more clear: "The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.").
0

Share this post


Link to post
Share on other sites

I can't say for certain unless I saw the code it was actually complaining about

Suitably obfuscated, but I think all the relevant information is preserved:
class X {
public:
    X(int i);
};

class Y {
    X mX;
    bool valid;

    const X & test() {
        if (!valid) {
            return X(0); // coverity reports illegal return of reference to temporary
        }
        return mX;
    }
};

but the standard specifically states that a temporary bound to the returned value in a function only persists until the function exits

Will that not in practice result in copy construction of a new temporary in the outer scope?
0

Share this post


Link to post
Share on other sites

Yeah, I'm pretty sure that Coverity is right on this one. The return X(0) creates a temporary that is destroyed at the end of the full expression of the return statement. The const reference in the outer scope will not create a new temporary because it isn't being initialized with an object, it's being initialized with another const reference. Even if it did know it needed to copy construct something, the end of a function is a sequence point and the object it would try to copy would already been destroyed.

0

Share this post


Link to post
Share on other sites
Interesting. Running the following with clang (previous work was with GCC):
 
#include <iostream>
 
class X {
  int mX;
  public:
    X(int i) : mX(i) { std::cout << "constructor" << std::endl; }
    ~X() { std::cout << "destructor" << std::endl; }
    X(const X &x) : mX(x.mX) { std::cout << "copy constructor" << std::endl; }
 
    int get() const { return mX; }
};
 
const X &getX() {
  std::cout << "in getX" << std::endl;
 
  return X(-123);
}
 
int main() {
  std::cout << "entering main" << std::endl;
 
  const X &x = getX();
 
  std::cout << "x: " << x.get() << std::endl;
 
  std::cout << "exiting main" << std::endl;
}
 
Results in the following output:
$ ./a.out 
entering main
in getX
constructor
destructor
x: -123
exiting main
Note that the destructor is in fact called when the getX() function exits, and before I attempt to access the member variable (which succeeds, I assume incidentally). Edited by swiftcoder
0

Share this post


Link to post
Share on other sites

Sounds right, you're basically returning a pointer. I get same result in VS2013 Express. However changing signature to const X getX() gives different result:

entering main
in getX
constructor
x: -123
exiting main
destructor

So it kinda did extend object's lifetime, just as OP said.

Edited by Zaoshi Kaba
0

Share this post


Link to post
Share on other sites
"Works" does not mean it's correct. It just means that the result of your undefined behavior happened to coincide with your expectations. Recompile, change compilers, change optimizations, etc. may all change the result.
 

const X &getX() {
  std::cout << "in getX" << std::endl;
 
  return X(-123);
}


This is illegal and undefined behavior. Period. That it works in some test means nothing other than that you got "lucky" (or more accurately, you got unlucky and got fooled into thinking the code is correct when it very much is not).

The reference is (under the hood) a pointer on the vast majority of C++ implementations. Ask yourself what it would be pointing to. In this case, it'll be pointing to a local variable which on most real-world machines means it's pointing to a memory address on the stack inside of getX(). Returning from the function doesn't destroy the stack; it just means that the address is now unused and the memory is now allowed to be reused by something else later on. If it appears to work, that's just because that address on the stack hasn't _yet_ been reused. You can likely find out how broken this code is by storing that reference, calling some other functions, and _then_ dereferencing the value:
 
// grab reference to stack value that is no longer "live"
const X& tmp = GetX();

// reuse the stack space for other calculations
some_other_non_trivial_function();

// dereference the tmp address and try to copy a value
// into the stack or a register (depends on calling
// conventions) for consumption by operator<<(ostream&, int)
std::cout << tmp.get();
Depending on optimizations and a bunch of other factors this is much more likely to print out total garbage (or even crash) when you write out the value of tmp as the address referenced by tmp will likely have been overwritten with something else.

You (and every C/C++ programmer) should read these slides on "Deep C" by Maudal and Jagger and fully internalize the information they present:
http://www.slideshare.net/olvemaudal/deep-c

I don't care if you have 20 years of experience and think you're the most bad-ass programmer around. Read those slides anyway. I lost count of how many multi-decade "veteran" C/C++ engineers I've worked with over the years that didn't know half of what those slides go over.
1

Share this post


Link to post
Share on other sites

Also, knowing the probable effects of undefined behaviour is no substitute for REMOVING the undefined behaviour from the code. In a real interview I'd be saying "don't write code like that, this is what you should do instead...".

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