Es gibt eine komplexe Klasse mit Konstruktor, die eine Nachricht für RVO druckt.
Ich habe Complex Operator + Methode in Gtest getestet.
Wenn RVO aufgetreten ist, druckt "Complex !!" Nachrichten für 3 mal.
Aber es gibt "Complex !!" Nachrichten für 5 mal.
RVO ist nicht aufgetreten, denke ich.
Ich habe diesen Code von C++ 98 und C++ 11
kompiliert Warum tritt RVO nicht auf?
Warum gilt RVO nicht in diesem Code
#include <stdio.h>
class Complex {
friend Complex operator+(const Complex&, const Complex&);
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) { printf("\nComplex!!\n");}
Complex(const Complex& c) : real(c.real), imag(c.imag) {}
Complex& operator=(const Complex& c) {
real = c.real;
imag = c.imag;
return *this;
}
~Complex() {}
private:
double real;
double imag;
};
Complex operator+(const Complex& lhs, const Complex& rhs)
{
return Complex(lhs.real + rhs.real, lhs.imag + rhs.imag);
}
int main()
{
Complex a(1.0), b(2.0), c;
for (int i = 0; i < 2; i++) {
c = a + b;
}
}
Es gibt 5 Konstruktoraufrufe: je einer für die Initialisierung von 'a',' b' und 'c', und einer für jeden Aufruf von' operator +'. Warum glaubst du, dass es eine andere Nummer geben würde? Welche sollte deiner Meinung nach nicht passieren? – immibis
RVO elides Aufrufe zum Kopieren von Konstruktoren und Verschieben von Konstruktoren, nicht andere. Dein Code sagt dir nichts über RVO. –
Es könnte auftreten für "Complex c = a + b;". Jetzt haben Sie nur eine Aufgabe, die nicht anwendbar ist. –