Search code examples
c++stringfunction-calls

Using constructor call as function parameter


Is it a good idea to use constructor calls as arguments? E.g. something like

doSomething(ClassA(someConstructorParameter));

Will the object be destroyed when the function terminates? Or if you have a function that takes a char* and you don't want it to mess up a string, would

someFunction(string(str).c_str());

be a bad idea?


Solution

  • The temporary will be destroyed at the end of the full expression, after the function returns. So it's fine as long as the function doesn't store a pointer or reference to the argument somewhere; that won't be valid later.