2011-12-09 36 views
0

我有一個對象構造函數中的一個常量指針const對象深度複製const的指針const對象

A::A(const B* const ex): m_B(B){}; 

其中M_B:

const B* const m_B; 

我現在想創建一個副本構造函數和賦值運算符 我已經嘗試了以下沒有任何運氣。

拷貝構造函數:

A::A(const A& cpy): *m_B(*cpy.m_B) {} 

這不工作...我怎麼處理這個? 作業運營商:

A& A::operator=(const A& rhs) { 

*m_B = *rhs.m_B // I know this won't work because const cannot be assigned 
       // error: assignment of read-only data-member 
} 

任何想法如何解決這個問題?

+0

複製構造函數就像任何其他構造函數一樣,並且不返回值。另外,'operator()'不是賦值,你複製/粘貼錯了嗎? –

+0

對不起,大量的錯別字。問題仍然存在 – MWright

+0

你的代碼沒有意義(仍然複製/粘貼錯誤)。請嘗試創建一個完整的,自包含的示例。另外,什麼不適用於你的第一種方法? –

回答

0

你的問題是,構造函數沒有返回值。

而賦值運算符是operator=而不是operator()

在你的構造函數中,你帶了一個指針並保存了指針,而不是指針指向的對象的內容。如果你把這個語義,你應該只複製指針而不是複製的內容:(或者你有別的事情來實現呢?)

class B; 

class A { 
public: 
    const B* m_b; 
    A(const B* const ex): m_B(ex){}; 

    //copy constructor 
    A(const A& cpy): m_B(cpy.m_B){}; 
    //assignment operator 
    A& operator=(const A&cpy) {m_B = cpy.m_B;}; 
}; 
+0

當你初始化m_b時,你正在做一個淺拷貝。這不是我不喜歡的複製對象超出範圍我有麻煩。還有沒有辦法繞過分配運營商? – MWright

+0

@fefe:const B * m_B不是const B * m_b – vrbilgi

+0

@fefe。我想我只會需要從構造函數中淺拷貝指針。謝謝,但賦值運算符仍然不成立,因爲它是隻讀數據成員的賦值。我想我會讓作業操作員保密。 – MWright

0

賦值運算符可能有機會與new創建一個新的實例:

A& A::operator=(const A& rhs) { 
    m_B = new B(rhs.m_B); 
    return *this; 
} 

當然,你必須跟蹤這個,所以你可以delete指針,如果你分配它。如果你不想跟蹤,也可以在構造函數中使用new

甚至更​​好,使用新的shared_ptr不必關心指針。

+0

this!= rhs自我分配檢查也可以添加 – vrbilgi

+0

@Joachim。指向B const的const指針已經分配給堆,所以我只用m_B指向它。對不起,我根本沒有說清楚這個問題 – MWright

2

如果你想深入複製,爲什麼你有一個指針?只需要一個原始對象。

class B{ 
    // ... 
}; 

class A{ 
    const B _b; 
public: 
    A(A const& other) 
    : _b(other._b) {} 

private: 
    // no assignment operator, since const objects can't be reassigned 
    A& operator=(A const&); // undefined 
}; 
+0

你可以每次從初始化列表中複製一個const類型嗎?所以像* m_B(* cpy.m_B)我知道這不起作用,但也許只是我的語法? – MWright

+0

@MWright:用指針,你需要分配新的內存'm_B(new B(* other.m_B))'。 – Xeo

+0

只是在const的啓動列表中。因爲我可以用* ptr_example = * cpy.ptr_example做一個指針的深層副本。謝謝! – MWright

0

分配具有常量指針的對象時,「placement new」操作符會很有用。

class ref 
{ 
public: 
    // Normal constructor creates new immutable reference. 
    ref(const char* const ptr, size_t len): m_ptr(ptr),m_len(len) {} 
    // Copy constructor creates new copy of existing immutable reference. 
    ref(const ref& o): m_ptr(o.m_ptr),m_len(o.m_len) {} 
    // Assignment operator replaces existing immutable reference with another one. 
    // Previous reference is gone. 
    ref& operator=(const ref& o) { new (this) ref(o.m_ptr, o.m_len); return *this; } 
private: 
    const char* const m_ptr; 
    size_t m_len; 
}