Vishal Kotcherlakota
Vishal Kotcherlakota

Reputation: 1154

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

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?

Upvotes: 6

Views: 264

Answers (2)

AlgebraWinter
AlgebraWinter

Reputation: 321

Ok you say it compiled and ran but didn't do anything. Does setPermissions() even get called, have you checked? It looks to me like the compiler has optimised out this entire line because you are working purely on a temporary object.

Upvotes: 0

Tomek
Tomek

Reputation: 4659

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.

Upvotes: 1

Related Questions