How to avoid Copy in Derived class operation? - c++

I have the following class structure:
class Base{
public:
Base() {}
Base(const Base& b){
cout << "Base Copy" << endl;
*this = b;
}
Base baseOperation(Base& base){
return Base();
}
};
class Derived : public Base{
public:
Derived(){}
Derived( const Base &d ) : Base(d)
{
cout << "Derived Copy: " << endl;
}
Derived operation(Derived& input){
return baseOperation(input);
}
};
Base is basically a library I am using. It has an operator called baseOperation, that takes in itself and returns an output; I want to wrap around that output but without making both a copy of base and of derived. It is making double copies now which slows my program down. Is there a way to avoid this

The only copy here could be while constructing Derived object in the return statement of
Derived operation(Derived& input){
return baseOperation(input);
}
All other copy operations are eliminated by RVO. Of course you can change copying to moving if you have access to sources of Base. But maybe it is worth to consider aggregation instead of inheritance.

Related

RVO when converting return value

I struggle with the complexity of conversions and casting, and I can't find advice online that clearly guarantees efficient conversion on function return. I have two classes, Base and Derived, where Derived has no extra data members over Base. I have a named constructor for the base class that I want to return using RVO and cast to an object of the derived type with as little overhead as possible.
class Base {
public:
static Base namedConstructor(int n){
return Base(n);
}
protected:
Base(int n) : member(n){
}
int member;
};
class Derived : public Base {
static Derived nC2(int n) {
Derived derived = namedConstructor(n);
// Error: no suitable user-defined conversion from "Base" to "Derived"...
// modify derived
return derived;
}
};
Is there a way to fix the error that satisfies all the following requirements?
No use of RTTI. Dynamic casting seems unnecessary.
Only one definition of namedConstructor in case I need to modify it. If necessary, I can make it a template, but I am interested in the alternatives.
namedConstructor should take advantage of RVO in nC2.
The conversion should not silently fail if I add or remove data members from either the base or the derived class (something similar to reinterpret_cast may do this).
Add a private ctor. to Derived, which constructs it from a Base:
Derived(const Base& base) : Base(base) {
}
If later you add extra member variables to Derived, initialize them also.
This is standard-compliant (although a little bit weird), and will be optimized away in release builds.
I've added constructors and with g++ 3.0 there is copy elision:
class Base {
public:
static Base namedConstructor(int n){
return Base(n);
}
protected:
Base(int n) : member(n){
std::cout << "Create Base" << std::endl;
}
Base (const Base & b) : member (b.member) {
std::cout << "Copy Base" << std::endl;
}
int member;
};
class Derived : public Base {
public:
Derived () : Base (0) {
std::cout << "Create Derived" << std::endl;
}
Derived (const Base & b) : Base(b) {
std::cout << "Create Derived from base" << std::endl;
}
int val () { return member; }
static Derived nC2(int n) {
return namedConstructor(n); //derived;
}
};
int main ()
{
Derived d = Derived::nC2(1);
std::cout << "Value: " << d.val() << std::endl;
return 0;
}
The output from this is:
Create Base
Copy Base
Create Derived from base
Value: 1
so one Base creation, one copy of Base when creating Derived and the Derived itself.
There are no copies from namedConstructor exit or nC2, nor for the assignment in main.
I've compiled this with -O0 but with those so small functions may be there is optimization here and those are removed.

Copy constructor needs base constructor with no arguments [duplicate]

Why aren't copy constructors chained (like default ctors or dtors) so that before the derived class's copy constructor is called, the base class's copy constructor is called? With default constructors and destructors, they are called in a chain from base-to-derived and derived-to-base, respectively. Why isn't this the case for copy constructors? For example, this code:
class Base {
public:
Base() : basedata(rand()) { }
Base(const Base& src) : basedata(src.basedata) {
cout << "Base::Base(const Base&)" << endl;
}
void printdata() {
cout << basedata << endl;
}
private:
int basedata;
};
class Derived : public Base {
public:
Derived() { }
Derived(const Derived& d) {
cout << "Derived::Derived(const Derived&)" << endl;
}
};
srand(time(0));
Derived d1; // basedata is initialised to rand() thanks to Base::Base()
d1.printdata(); // prints the random number
Derived d2 = d1; // basedata is initialised to rand() again from Base::Base()
// Derived::Derived(const Derived&) is called but not
// Base::Base(const Base&)
d2.printdata(); // prints a different random number
The copy constructor doesn't (can't) really make a copy of the object because Derived::Derived(const Derived&) can't access basedata to change it.
Is there something fundamental I'm missing about copy constructors so that my mental model is incorrect, or is there some arcane (or not arcane) reason for this design?
The copy constructor doesn't (can't) really make a copy of the object because Derived::Derived(const Derived&) can't access pdata to change it.
Sure it can:
Derived(const Derived& d)
: Base(d)
{
cout << "Derived::Derived(const B&)" << endl;
}
If you don't specify a base class constructor in the initializer list, its default constructor is called. If you want a constructor other than the default constructor to be called, you must specify which constructor (and with which arguments) you want to call.
As for why this is the case: why should a copy constructor be any different from any other constructor? As an example of a practical problem:
struct Base
{
Base() { }
Base(Base volatile&) { } // (1)
Base(Base const&) { } // (2)
};
struct Derived : Base
{
Derived(Derived&) { }
};
Which of the Base copy constructors would you expect the Derived copy constructor to call?
You can:
Derived(const Derived& d) : Base(d) {
cout << "Derived::Derived(const B&)" << endl;
}
This calls the Base copy constructor on the Base sub-object of d.
The answer for 'why' I don't know. But usually there's no answer. The committee just had to choose one option or the other. This seems more consistent with the rest of the language, where e.g. Derived(int x) won't automatically call Base(x).
That's because every constructor calls by default the default base constructor:
Derived(const Derived& d) {
cout << "Derived::Derived(const B&)" << endl;
}
will call Base().
This is defined by the standard. I for one prefer it like this rather than calling the copy constructor on the class. You can of course call it explicitly.

Copy constructing from a derived object

In the following code, the function foo is copy constructing a Base object c from a Derived object d. My question is: are we getting an exact copy? Because I'm not getting the polymorphic behavior I'm expecting
#include<iostream>
class Base
{
public:
virtual void sayHello()
{
std::cout << "Hello Base" << std::endl ;
}
};
class Derived: public Base
{
public:
void sayHello() override
{
std::cout << "Hello Derived" << std::endl ;
}
};
void foo(Base* d)
{
Base* c = new Base(*d);
c->sayHello() ;
}
int main()
{
Derived d;
foo(&d) ; //outputs Hello Base
}
There is no virtual constructor nor copy constructor.
However, it is possible to define a function that behaves like one.
In my case, it is the virtual member function copy() which I added to OP's sample:
#include <iostream>
class Base
{
public:
virtual Base* copy() const { return new Base(*this); }
virtual void sayHello()
{
std::cout << "Hello Base" << std::endl ;
}
};
class Derived: public Base
{
public:
virtual Base* copy() const override { return new Derived(*this); }
void sayHello() override
{
std::cout << "Hello Derived" << std::endl ;
}
};
void foo(Base* d)
{
Base* c = d->copy();
c->sayHello() ;
}
int main()
{
Derived d;
foo(&d) ; //outputs Hello Derived
return 0;
}
Output:
Hello Derived
Live Demo on coliru
The drawback is that every derived class of Base has to provide it to make it function properly. (I've no idea how to convince the compiler to check this for me with any trick.)
A partial solution could be to make copy() pure virtual in the class Base (assuming it is not meant to be instantiable).
you may wonna change the line of new
Base* c = new Derived(*d);
so you have the type Derived in a Base pointer. During runtime it is looked up, which type it is and you get the right output.
let me know if im wrong... just created this out of my mind on the fly.
To answer your question about whether or not this is copy constructing lets add some members. Base will have a member, m_b and Derived will inherit m_b but also have another member m_d
#include <iostream>
struct Base {
const int m_b;
Base() = delete;
Base(const int a_b) : m_b(a_b) {}
virtual void sayHello() {
std::cout << "Base " << m_b << std::endl;
}
};
struct Derived : public Base {
const int m_d;
Derived() = delete;
Derived(const int a_b, const int a_d) : Base(a_b), m_d(a_d) {}
void sayHello() override {
std::cout << "Derived " << m_b << ' ' << m_d << std::endl;
}
};
void foo(Derived* a) {
Base* b = new Base(*a);
b->sayHello(); // Output is "Base 1", 1 was copied from argument a
}
void bar(Derived* a) {
Base* d = new Derived(*a);
d->sayHello(); // Output is "Derived 1 2"
}
int main() {
Derived d(1, 2);
foo(&d);
bar(&d);
return 0;
}
The line:
Base* b = new Base(*a);
Created a Base and so sayHello calls Base's implementation which doesn't know about m_d. However this line does copy m_b from the derived class
The line:
Base* d = new Derived(*a);
Created a Derived and so sayHello calls Derived's implementation which copied both m_b and m_d
Expected polymorphic behavior will come into existence when the Base class pointer points to Derived class object. Then at run time the actual type of object pointed to by the Base class pointer will be checked and appropriate function will get called.
Base* c = new Base(*d); // <<-- case of object slicing
Here, c points to Base class object. Therefore, c->sayHello() ; is bound to call the Base::sayHello() at runtime.
are we getting an exact copy?. No since you are creating a Base object due to new Base. Due to object slicing the Base part of the *d object is passed to copy c'tor and what you get is corresponding Base object.
Base *c = new Derived(*d); will give the expected behavior.

Polymorphism in C++ does not work correctly with reference

I have a simple code which doesn't work correctly with reference (polymorphism).
#include <iostream>
#include <string>
class Base {
public:
Base() {}
virtual ~Base() {}
virtual std::string text() const {
return "Base";
}
};
class Derived: public Base {
public:
Derived(Base& _b): b(_b) {}
virtual ~Derived() {}
virtual std::string text() const {
return b.text() + " - Derived";
}
private:
Base& b;
};
int main(int argc, char const *argv[])
{
Base b;
Derived d1(b);
std::cout << d1.text() << std::endl;
Derived d2(d1);
std::cout << d2.text() << std::endl;
return 0;
}
And output:
Base - Derived
Base - Derived
The second line in output I expected: Base - Derived - Derived. I read some resources and polymorphism work perfectly with reference and pointer but in this situation, it doesn't. If I replace reference by pointer, it work again. So, anybody can give me some explainations?
Thanks so much!
You're invoking the default copy constructor to Derived. Therefore when finished d2 will be a simple member-copy of d1, and both their b members will reference the same Base instance.
To prove this, add this to your Derived class
class Derived: public Base {
public:
Derived(Derived& d) : b(d) {}
Derived(Base& _b): b(_b) {}
virtual ~Derived() {}
virtual std::string text() const {
return b.text() + " - Derived";
}
private:
Base& b;
};
With this your output will become:
Base - Derived
Base - Derived - Derived
And just note, this is not a grand idea or a stellar learning example of polymorphism. (But it is an interesting example of construction overriding). Also note this is NOT a typical override of default copy-construction (where the parameter is a const-ref-type). Thus part of the reason this is not the greatest sample.
If you instrument the code you will see that when you call Derived d2(d1) the Derived::Derived(Base&)
constructor is not being called. This is because the d1 argument is a better match for the
implicit copy constructor, which just copies the b member from d1 to d2.
In order to see the behavior you expect, you can explicitly cast the d1 to (Base&)d1. If you do
so you will get code like the following (with the instrumentation):
#include <iostream>
#include <string>
class Base {
public:
Base() {}
virtual ~Base() {}
virtual std::string text() const {
return "Base";
}
};
class Derived: public Base {
public:
Derived(Base& _b): b(_b) {std::cout << "init'ed with: " << _b.text() << std::endl;}
virtual ~Derived() {}
virtual std::string text() const {
return b.text() + " - Derived";
}
private:
Base& b;
};
int main(int argc, char const *argv[])
{
std::cout << "Creating Base" << std::endl;
Base b;
std::cout << "Creating d1" << std::endl;
Derived d1(b);
std::cout << d1.text() << std::endl;
std::cout << "Creating d2" << std::endl;
Derived d2(d1);
std::cout << d2.text() << std::endl;
std::cout << "Creating d3" << std::endl;
Derived d3((Base&)d1);
std::cout << d3.text() << std::endl;
return 0;
}
And this gives the expected output:
Creating Base
Creating d1
init'ed with: Base
Base - Derived
Creating d2
Base - Derived
Creating d3
init'ed with: Base - Derived
Base - Derived - Derived
Your d1 and d2 both have type Derived so this is working correctly. Typically the references are reversed; e.g.
Base b;
Derived d;
Base &dr = d;
std::cout << b.text() << std::endl;
std::cout << dr.text() << std::endl;
Here text() is invoked through a Base type but the latter will call the version in Derived.
Note that it doesn't typically make sense to allow a derived class to be initialized via a base class. Suppose you add type Derived2 that has abilities or state much different from Derived. This constructor would allow
Derived2 d2;
Derived d1(d2);
which is likely a very bad idea.
As noted correctly in the comment, it is now using the default copy constructor, and that is the reason for your observation with the same output for both. So, d1 is just copied into d2 rather than used for the base member variable inside d2.

Why doesn't a derived class use the base class operator= (assignment operator)?

Following is a simplified version of an actual problem. Rather than call Base::operator=(int), the code appears to generate a temporary Derived object and copy that instead. Why doesn't the base assignment operator get used, since the function signature seems to match perfectly? This simplified example doesn't display any ill effects, but the original code has a side-effect in the destructor that causes all kinds of havoc.
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base()\n";
}
Base(int)
{
cout << "Base(int)\n";
}
~Base()
{
cout << "~Base()\n";
}
Base& operator=(int)
{
cout << "Base::operator=(int)\n";
return *this;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived()\n";
}
explicit Derived(int n) : Base(n)
{
cout << "Derived(int)\n";
}
~Derived()
{
cout << "~Derived()\n";
}
};
class Holder
{
public:
Holder(int n)
{
member = n;
}
Derived member;
};
int main(int argc, char* argv[])
{
cout << "Start\n";
Holder obj(1);
cout << "Finish\n";
return 0;
}
The output is:
Start
Base()
Derived()
Base(int)
Derived(int)
~Derived()
~Base()
Finish
~Derived()
~Base()
http://ideone.com/TAR2S
This is a subtle interaction between a compiler-generated operator= method and member function hiding. Since the Derived class did not declare any operator= members, one was implicitly generated by the compiler: Derived& operator=(const Derived& source). This operator= hid the operator= in the base class so it couldn't be used. The compiler was still able to complete the assignment by creating a temporary object using the Derived(int) constructor and copy it with the implicitly generated assignment operator.
Because the function doing the hiding was generated implicitly and wasn't part of the source, it was very hard to spot.
This could have been discovered by using the explicit keyword on the int constructor - the compiler would have issued an error instead of generating the temporary object automatically. In the original code the implicit conversion is a well-used feature, so explicit wasn't used.
The solution is fairly simple, the Derived class can explicitly pull in the definition from the Base class:
using Base::operator=;
http://ideone.com/6nWmx