我使用base-from-member成語,我現在堅持與他們複製/移動構造函數。假設下面的代碼:這裏複製/移動構造函數的基礎成員成語
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
using namespace std;
struct A // base class
{
A(string &s) : s(s), c(0) { };
A(const A &a) : s(a.s), c(a.c) { };
void print() { cout << s << endl; c++; }
int print_count() { return c; }
string &s;
int c;
};
struct B_base // this class will be initialized before A
{
B_base(int i)
{
s = boost::lexical_cast<string>(i);
}
B_base(const B_base &other) : s(other.s) { };
string s;
};
struct B : B_base, A // main class
{
B(int i) : B_base(i), A(B_base::s) { }
B(const B &other) : B_base(other), A(other) { } // <-- problem here
using A::print;
using A::print_count;
};
int main()
{
B b(10);
b.print(); // prints '10'
cout << b.print_count() << endl; // prints '1'
B b1(b);
b1.print(); // prints '10'
A &a = b;
a.s = "FAIL"; // we modify b, not b1 here!
b1.print(); // but b1 prints 'FAIL' here --- error (it should still print '10')
cout << b.print_count() << " " << b1.print_count() << endl; // prints '1 3'
return 0;
}
問題是,參考A.s
(其是指向B_base::s
)被複制從一個實例到另一個,而應該被修改爲指向另一個B_base::s
。如果先前的實例超出了以懸空引用結尾的範圍,情況可能更糟。
我的問題是:如何使用基於成員的成語製作正確的副本? (我認爲移動構造函數將類似於複製一個,對不對?)
A(const的A&A):S(A.S),...其中弦&S不是const的?你可以修改一個使用s。 – qPCR4vir 2013-02-11 18:31:51