Objects in var. length arguments (?)

A

Alvaro Segura

Hello,

I have this doubt that I find no answer for:

Can an object or a reference to an object be passed as an argument to a
variable length arguments function? And if so, how does it work?

// suppose we have:
void f(int x, ...);
class A {};

// and we do:
A a;
f(3, a); // is this OK?

I recently found that MSVC++ was not complaining when I accidentally did
something like that, but I thought it was wrong. What about the standard?
 
M

Michael Kochetkov

Alvaro Segura said:
Hello,

I have this doubt that I find no answer for:

Can an object or a reference to an object be passed as an argument to a
variable length arguments function? And if so, how does it work?

// suppose we have:
void f(int x, ...);
class A {};

// and we do:
A a;
f(3, a); // is this OK?

I recently found that MSVC++ was not complaining when I accidentally did
something like that, but I thought it was wrong. What about the standard?
Your code is OK. It is the f's problem to find A object on the stack. The
common solution is to pass a kind of a format information to f.
 
R

Ron Natalie

Michael Kochetkov said:
Your code is OK. It is the f's problem to find A object on the stack. The
common solution is to pass a kind of a format information to f.

In this case, since A is of POD type, it is ok.
Had the class A been been a little bit more elaborate (so as to make it non-POD)
it would have been undefined behavior.
 
V

Victor Bazarov

Alvaro Segura said:
I have this doubt that I find no answer for:

Can an object or a reference to an object be passed as an argument to a
variable length arguments function? And if so, how does it work?

An object can, but only if the object is of POD type. A reference
probably cannot.
// suppose we have:
void f(int x, ...);
class A {};

// and we do:
A a;
f(3, a); // is this OK?

Yes, class A is a POD.
I recently found that MSVC++ was not complaining when I accidentally did
something like that, but I thought it was wrong. What about the standard?

The Standard says that if it's not POD, the behaviour is undefined.
See 5.2.2/7.

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top