Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I chain a method to a constructor?

Tags:

c++

object

qt

I'm trying to set a permission for a file. I thought I could save a line of code while dealing with a QFile object, like so.

QFile("somefile.txt").setPermissions(QFile::WriteOther);

It compiled and ran, but didn't do anything. Of course, when I did it the right way, it worked. (no surprise, there.)

QFile tempFileHandle("somefile.txt");
tempFileHandle.setPermissions(QFile::WriteOther);

I think this is a good opportunity to understand the C++ syntax. I'll accept that my original way doesn't work, but why?

like image 541
Vishal Kotcherlakota Avatar asked Nov 07 '12 00:11

Vishal Kotcherlakota


1 Answers

Well, I don't know QFile and don't know exactly what your observation is but it probably boils down to whatever is done in QFile's destructor.

The first example creates temporary object. I guess its constructor creates somefile.txt. Then setPermissions sets whatever you specified on that file. Now the question is what destructor does:

  • It may delete file, and you see nothing
  • It may (I wouldn't expect this but who knows) set file read only
  • Revert to some defaults

In the other example you create named variable which is not destroyed until it goes out of scope and you probably can even detach the object from the file on disk which will probably nullify destructor effects on that file.

like image 120
Tomek Avatar answered Oct 12 '22 19:10

Tomek