POV-Ray : Newsgroups : povray.off-topic : Saw a weird C++ construct I'm not sure I understand... : Re: Saw a weird C++ construct I'm not sure I understand... Server Time
7 Sep 2024 03:19:22 EDT (-0400)
  Re: Saw a weird C++ construct I'm not sure I understand...  
From: Warp
Date: 20 Aug 2008 18:34:01
Message: <48ac9bd9@news.povray.org>
Darren New <dne### [at] sanrrcom> wrote:
> (Indeed, it took me a couple minutes to even figure out how it would 
> exit *after* printing stuff if the assertion failed. But then I'm not a 
> C++ kind of person.)

  Yes, the lifetime of the temporary object created by the assert() macro
may not be completely trivial to understand.

  This is a very simplified version of the situation:

//-------------------------------------------------------------------------
class Test
{
 public:
    Test() { std::cout << "constructor\n"; }
    ~Test() { std::cout << "destructor\n"; }

    Test& foo(int i)
    {
        std::cout << i << std::endl;
        return *this;
    }
};

int main()
{
    std::cout << "Before\n";
    Test().foo(1).foo(2).foo(3); // *
    std::cout << "After\n";
}
//-------------------------------------------------------------------------

  The line marked with * above creates a nameless temporary instance of
the class Test. Obviously it's constructed at that location. However,
where is it destroyed? Is it destroyed before or after the "After"
printing line? If it's destroyed before, is it valid to repeatedly call
its foo() function, which returns a reference to itself?

  We get an answer by running the program. It prints:

Before
constructor
1
2
3
destructor
After

  This starts being slightly advanced C++, and thus not for the feint
of heart.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.