If a constructor B()
is called to create a temporary object, e.g. in a call f(B().name())
, will the construction of B
always carried out, or are compilers permitted and able to optimize out unnecessary allocations that go along with object creation?
Specific example:
class A {
public:
virtual std::string name() = 0;
};
class B : public A {
public:
std::string name() final { return "MyClassName"; }
// cannot be made static, because at some places we need
// the polymorphic call from A-pointers
private:
int data;
...
// members that require heap allocation
};
int main() {
std::cout << "Class B is named " << B().name() << std::endl;
}
Will the last statement actually create an instance of B
, including allocation of storage for B().data
?