Does temporary object creation depends on the C++ compiler?
Does temporary object creation depends on the compiler?
In the code bellow, I call a function sending a char* but the function requires an Object reference. However, Object has a constructor that uses a char*.. So a temporary object is automatically created and send to the print function.
class Object {
string text;
public:
Object ( const char* value ) { text = value; }
void print() const { printf( "[%s]\n", text.c_str() ); }
};
void print( const Object& obj ) { obj.print(); }
int main() {
print( "hello" );
}
Does this behavior开发者_StackOverflow depends on the compiler? You can see the output here: http://codepad.org/AABw5Ulz
Your case is pretty clear-cut. This isn't even a situation where temporaries may or may not be elided. Rather, your print
function requires an Object
-type argument, so one will necessarily have to be constructed.
There isn't any room for alternatives in your situation, so there's nothing that could depend on a compiler. If you wanted a situation that left room for optimizations, you could consider passing the argument by value: void print(Object);
. Now it's up to the compiler whether the temporary object gets copied once or constructed directly in the target function. That's because copy constructors are explicitly allowed to be elided.
When you declare such a constructor
Object ( const char* value )
it means the compiler can do an implicit conversion.
So no it is not a compiler dependent feature but it is by desing.
The compiler is simply allowed to take your "hello"
and pass it to the Object
contructor before sending it to the print(const Object &obj)
function.
精彩评论