Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens if I pass a struct to a vararg function?

void f(int count, ...){
    //whatever
}

struct somestruct{
    size_t a, b, c;
};

int main() {
    somestruct s;
    f(1, s);    //what is actually passed?
}

Is the entire struct copied and passed on the stack? If so are copy constructors called? Is the pointer passed? Is this safe?

like image 661
Lorenzo Pistone Avatar asked Nov 04 '12 01:11

Lorenzo Pistone


2 Answers

Yes, if you pass an lvalue, the lvalue to rvalue conversion will be done, which means calling the copy constructor to copy the object into a new copy and passing that as an argument.

like image 62
Johannes Schaub - litb Avatar answered Oct 20 '22 08:10

Johannes Schaub - litb


void f(...) is using bit-wised copy. No default constructor or copy constructor will be generated for your somestruct as it only has C++ build-in types.

Is this safe?

Yes, this is perfectly safe.

I'll refer you to 'Inside C++ Object Model' chapter 2 The Semantics of Constructors

like image 44
billz Avatar answered Oct 20 '22 06:10

billz