2

Consider the following code.

struct MyImage
{
    MyImage(const int handle);
    MyImage(const CString& filePath);
    virtual ~MyImage();

    void Process();
    void SaveAs(const CString& filePath);

    // No copying!
    MyImage(const MyImage& other) = delete;
    MyImage& operator=(const MyImage& other) = delete;
}

void ProcessImageFile(const CString& inFilePath, const CString& outFilePath)
{
    MyImage& image = MyImage(-1); // initialized with invalid handle

    if (DecryptionRequired())
    {
        const CString tempFilePath = ::GetTempFileName();
        Decrypt(inFilePath, tempFilePath);
        image = MyImage(tempFilePath);
        _tremove(tempFilePath);
    }
    else
    {
        image = MyImage(inFilePath);
    }

    image.Process();
    image.SaveAs(outFilePath);
}

Will the object referenced by image be destructed when ProcessImageFile() returns?

piedar
  • 2,599
  • 1
  • 25
  • 37

1 Answers1

6
MyImage& image = MyImage(-1); // initialized with invalid handle

Should not compile as you cannot take a non const reference to a temporary variable. If you had

const MyImage& image = MyImage(-1); // initialized with invalid handle

Then the liftime would be extended untill the reference's lifetime ends. Since the reference variable is an automatic object the lifetime will end when it goes out of scope. From [basic.stc.auto]

Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

As for why Visual studio is allowing this see Non-const reference bound to temporary, Visual Studio bug?

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402