Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Temporary object" warning - is it me or the compiler?

The following snippet gives the warning:

[C++ Warning] foo.cpp(70): W8030 Temporary used for parameter '_Val' in call to 'std::vector<Base *,std::allocator<Base *> >::push_back(Base * const &)'

.. on the indicated line.

class Base
{
};

class Derived: public Base
{
public:
 Derived()   // << warning disappears if constructor is removed!
 {
 };
};

std::vector<Base*> list1;
list1.push_back(new Base);
list1.push_back(new Derived);  // << Warning on this line!

Compiler is Codegear C++Builder 2007.

Oddly, if the constructor for Derived is deleted, the warning goes away... Is it me or the compiler?

EDIT: The only way I've found to remove the warning is to something similar to this:

Derived * d;
list1.push_back(d = new Derived);  // << No warning now...
like image 759
Roddy Avatar asked May 25 '10 14:05

Roddy


2 Answers

Simple try:

list1.push_back(new Derived());

I am afraid there is something about POD (with trivial constructors) vs non-POD going on here.

EDIT:

Given that the code compiles fine with gcc.3.4.2 (--pedantic) I would say it's a compiler quirk. I am leaning toward MarkB explanation, ie the compiler creating a temporary even though I don't understand why it would be required and then complaining when assigning it to the const&... but I'm still perplex.

like image 93
Matthieu M. Avatar answered Nov 14 '22 12:11

Matthieu M.


In a "pass by reference" call, if the argument type does not match the "formal parameter", then the compiler will try to convert the argument to the correct type. The argument will be considered as a 'value parameter' if the conversion is successful. The compiler generates the warning "Temporary used for ..." in this case.

like image 2
Behnam Dezfouli Avatar answered Nov 14 '22 11:11

Behnam Dezfouli