Consider following diamond-like multiple inheritance:
class base;
class d1 : virtual public base;
class d2 : virtual public base
class d3 : public d1, public d2;
base is a move-only class (having a large move-only buffer). So are d1, d2 and d3. Move constructor of d1 and d2 call move constructor of the base.
Then what should do move constructor of d3? Calling both move-ctors of d1 and d2 results in crashs (since move constructor of base is called twice.
Here I have a minimum compilable instance of the problem:
#include <iostream>
struct moveonly {
moveonly(): data(nullptr) {}
moveonly(const moveonly &) = delete;
moveonly(moveonly &&other) {
this->data = other.data;
other.data = nullptr;
}
~moveonly() {
if(data)
delete[] data;
}
char *data;
};
class base {
public:
base() = default;
base(const base &) = delete;
base(base &&other) : d(std::move(other.d)) { }
virtual ~base() = default;
int a;
int b;
moveonly d;
};
class d1 : virtual public base {
public:
d1() = default;
d1(const base &) = delete;
d1(d1 &&other) : base(std::move(other)) { }
int x;
int y;
};
class d2 : virtual public base {
public:
d2() = default;
d2(const base &) = delete;
d2(d2 &&other) : base(std::move(other)) { }
int r;
int s;
};
class d3 : public d1, public d2 {
public:
d3() = default;
d3(const base &) = delete;
// What should I do here?
d3(d3 &&other) : d1(std::move(other)), d2(std::move(other)) { }
int p;
int q;
};
int main()
{
d3 child;
child.d.data = new char[1024];
for(size_t i = 0; i < 1024; ++i)
child.d.data[i] = i * 2;
d3 other_child = std::move(child);
for(size_t i = 0; i < 1024; ++i) {
std::cerr << other_child.d.data[i] << ' ';
}
std::cerr << std::endl;
return 0;
}
As with all virtual inheritance, the virtual bases are initialized by the most-derived object, so:
d3(d3 &&other)
: base(std::move(other)), // <== *you* initialize the base
d1(std::move(other)),
d2(std::move(other)) {}
What's wrong with asking the compiler to provide the implementation?
d3(d3 &&) = default; // I think this the best approach as it is less error pron .
You could write it out if you really wanted to:
d3(d3 &&other): base(std::move(other)), d1(std::move(other)), d2(std::move(other))
{
}
Related
move derived obj d to derived dd, but match base's move constructor, do not match derived's constructor
// base class
class base {
int x;
public:
base() = default;
base(base && b) {
x = b.x;
}
};
// derived struct
struct derived : public base {
int y;
derived(int d) {
y = d;
}
derived() = default;
};
int main()
{
derived d{1};
derived dd = std::move(d);
spdlog::info(dd.y); // => 1
return 0;
}
I do not know why dd.y will be 1, not 0 ?
how d.y copied to dd.y struct ?
My question is very similar like other's, but a bit different. I have a sample code:
class B1 {
private :
int * ptr;
public:
B1() : a{ 1 } { ptr = new int{ 2 }; }
B1(const B1& other) : a{ other.a } { ptr = new int{ *other.ptr }; }
~B1() { delete ptr; }
int a;
virtual void smthing() = 0;
};
class D : B1 {
public:
D(int i) : B1{} {}
D(const D& a) : B1{ a } {}
void smthing() { return; };
};
int main() {
D d { 3 };
D dd { d };
return 0;
}
I am using vs2015, and this code is works, but gives me error: object of abstract class type "B1" is not allowed...
If I remove this line D(const D& a) : B1{ a } {}, the base class copy constructor is called and there's no problem, but if I need the derived class copy constructor how can I make this work without error?
Thanks for the answer!
I have a base class Base and a derived class D, and I'd like to have move constructor and move assignment operator automatically generated by the compiler for me. Following the Rule of Zero, I leave all memory management to the compiler and only use level-2 classes (no raw pointers, arrays, etc.):
#include <iostream>
class Base{
public:
Base(): a_(42) {}
virtual void show() { std::cout << "Base " << a_ << std::endl; }
private:
int a_;
};
class D : Base {
public:
D(): b_(666) {}
void show() { std::cout << "D " << b_ << std::endl; }
private:
int b_;
};
int main() {
Base b;
b.show();
D d;
d.show();
return 0;
}
This should be it, right?
Enter the C++ core guidelines:
A base class destructor should be either public and virtual, or protected and nonvirtual.
Ah, so I guess I'll have to add a destructor to Base. But that'll do away with the automatically generated move functions!
What's the clean way out here?
You can = default everything that you would like to be generated by the compiler.
See (at the bottom): http://en.cppreference.com/w/cpp/language/rule_of_three
In your case it could look something like:
class Base{
public:
Base(): a_(42) {}
Base(const Base&) = default;
Base(Base&&) = default;
Base& operator=(const Base&) = default;
Base& operator=(Base&&) = default;
virtual ~Base() = default;
virtual void show() { std::cout << "Base " << a_ << std::endl; }
private:
int a_;
};
You can create once a class like
struct VirtualBase
{
virtual ~VirtualBase() = default;
VirtualBase() = default;
VirtualBase(const VirtualBase&) = default;
VirtualBase(VirtualBase&&) = default;
VirtualBase& operator = (const VirtualBase&) = default;
VirtualBase& operator = (VirtualBase&&) = default;
};
And then follow rule of zero:
class Base : VirtualBase
{
public:
Base(): a_(42) {}
virtual void show() { std::cout << "Base " << a_ << std::endl; }
private:
int a_;
};
class Base
{
private:
int _b;
public:
Base();
Base(int b);
virtual void display();
//Assignment operator overload.
Base& operator=(const Base&);
};
Base::Base()
{
_b = 0;
}
Base::Base(int b)
{
_b = b;
}
void Base::display()
{
cout<<"base value := "<<_b<<endl;
}
Base& Base::operator=(const Base& ob)
{
//Check for self-assignment.
if(this != &ob)
{
this->_b = ob._b;
}
return *this;
}
class Derived : public Base
{
private:
int _d;
public:
Derived();
Derived(int d);
void display();
//Assignment operator overload.
Derived & operator=(const Derived& ob);
};
Derived::Derived() : Base()
{
_d = 0;
}
Derived::Derived(int d) : Base(d)
{
_d = d;
}
void Derived::display()
{
cout<<"Derived value := "<<_d<<endl;
}
Derived & Derived::operator=(const Derived& ob)
{
if(this != &ob)
{
this->_d = ob._d;
}
return *this;
}
int main()
{
Derived d1(10),d2(),d3;
//How d2 becomes lvalue and not d3 above.
d2 = d1;//Error :: expression must be modified lvalue.
//d2.display();
d3 = d1;
return 0;
}
Derived d2();
is treated as function declaration. Do this :-
Derived d1(10),d2,d3;
d2 = d1; /////ahaa it's working
The problem is your 'd2()'. The statement d2() does not create a derived object called d2 like you think it does. The correct options are:
Derived d2;
Derived d2 = Derived();
Derived d2(0); // or any other integer
The statement
Derived d2();
tells the compiler that you are defining a function which takes no arguments and returns the type Derived.
See here for a longer explanation:
error: request for member '..' in '..' which is of non-class type
As is talked about in Item 33 in "More Effective C++", the assignment problem is
//Animal is a concrete class
Lizard:public Animal{};
Chicken:public Animal{};
Animal* pa=new Lizard('a');
Animal* pb=new Lizard('b');
*pa=*pb;//partial assignment
However, if I define Animal as an abstract base class, we can also compile and run the sentence:*pa=*pb. Partial assignment problem is still there.
See my example:
#include <iostream>
class Ab{ private: int a;
double b;
public:
virtual ~Ab()=0;
};
Ab::~Ab(){}
class C:public Ab{
private:
int a;
double b;
};
class D:public Ab{
private:
int a;
double b;
};
int main()
{
Ab *pc=new C();
Ab *pd=new D();
*pc=*pd;
return 0;
}
Do I miss something? Then what's the real meaning of the abstract base class?
I got the answer by myself. I missed a code snippet in the book.
Use protected operator= in the base class to avoid *pa=*pb. Use abstract base class to avoid animal1=animal2.Then the only allowed expressions are lizard1=lizard2;chicken1=chicken2;
See the code below:
#include <iostream>
class Ab{
private:
int a;
double b;
public:
virtual ~Ab()=0;
protected: //!!!!This is the point
Ab& operator=(const Ab&){...}
};
Ab::~Ab(){}
class C:public Ab{
public:
C& operator=(const C&){...}
private:
int a;
double b;
};
class D:public Ab{
public:
D& operator=(const D&){...}
private:
int a;
double b;
};
int main()
{
Ab *pc=new C();
Ab *pd=new D();
*pc=*pd;
return 0;
}
The abstract base class cannot help in case of assignment because the base sub-object is not instantiated (what an abstract class would block) but is sliced off the derived object (i.e. the assignment is done between already existing base sub-objects).
To avoid the problem the only solution I can think to is
make the assignment virtual
check in the assignment that the source instance is of the correct type
In code
#include <iostream>
struct Base {
int bx;
Base(int bx) : bx(bx) {}
virtual Base& operator=(const Base& other) {
bx = other.bx;
return *this;
}
};
struct A : Base {
int x;
A(int bx, int x) : Base(bx), x(x) {}
A& operator=(const Base& other) {
const A& other_a = dynamic_cast<const A&>(other);
Base::operator=(other);
x = other_a.x;
return *this;
}
};
struct B : Base {
int x;
B(int bx, int x) : Base(bx), x(x) {}
B& operator=(const Base& other) {
const B& other_b = dynamic_cast<const B&>(other);
Base::operator=(other);
x = other_b.x;
return *this;
}
};
The dynamic_cast<const A&>(other) is the operation that will fail if the object passed to the assignment operator is not of the correct derived type (it can be a sub-derived object, but this should be logically ok for an assignment source).
As an example:
int main(int argc, const char *argv[]) {
Base *pa1 = new A(1, 2);
Base *pa2 = new A(3, 4);
Base *pb1 = new B(5, 6);
Base *pb2 = new B(7, 8);
*pa1 = *pa2; std::cout << pa1->bx << "/" << dynamic_cast<A*>(pa1)->x << "\n";
*pb1 = *pb2; std::cout << pb1->bx << "/" << dynamic_cast<B*>(pb1)->x << "\n";
std::cout << "Ok so far\n";
*pa1 = *pb1; // Runtime error here (bad cast)
return 0;
}
It doesn't matter that your base class has pure virtual functions because you haven't defined the operator= for any of the classes. So when the compiler sees this statement:
*pc=*pd;
where pc and pd are both of type Ab, it will call the default assignment operator for Ab, which will result in partial assignment. As in the following example, I get the output as "Abstract Base" which is from abstract base class:
class A {
public:
virtual void foo() =0;
virtual A& operator=(const A& rhs) {
std::cout << "Abstract Base";
return *this;
}
};
class B : public A {
public:
virtual void foo() {
std::cout << "b:foo";
}
};
class C : public A {
public:
virtual void foo() {
std::cout << "c:foo";
}
};
int main()
{
A* b = new B();
A* c = new C();
*b = *c;
return 0;
}
Since you have not handled the assignment operators in your classes, you land up in situation partial assignment as Scot clearly describes in his article.
You need to handle assignments in your classes. In current design default implicit assignment operator of Ab is called and thus all the properties of children class are lost.
To avoid this you should have an implementation like this:
class Ab{ private: int a;
double b;
public:
virtual ~Ab()=0;
virtual Ab& operator=(const Ab& rhs){cout<<"in Ab="<<endl;}
};
Ab::~Ab(){}
class C:public Ab{
C& operator=(const Ab& rhs){cout<<"in C="<<endl;
return operator=(dynamic_cast<const C&>(rhs)); }
C& operator=(const C& rhs){
cout<<"do somethin in C="<<endl;
}
private:
int a;
double b;
};
class D:public Ab{
D& operator=(const Ab& rhs){cout<<"in D="<<endl;
return operator=(dynamic_cast<const D&>(rhs)); }
D& operator=(const D& rhs){
cout<<"do somethin in D="<<endl;
}
private:
int a;
double b;
};