#include <iostream>
class A{
public:
A(){std::cout << "basic constructor called \n";};
A(const A& other) {
val = other.x
std::cout << "copy constructor is called \n";
}
A& operator=(const A& other){
val = other.x
std::cout << "\n\nassignment operator " << other.val << "\n\n";
}
~A(){
std::cout << "destructor of value " << val <<" called !!\n";
}
A(int x){
val = x;
std::cout << " A("<<x<<") constructor called \n";
}
int get_val(){
return val;
}
private:
int val;
};
int main(){
// non pointer way
A a;
a = A(1);
std::cout << a.get_val() << std::endl;
a = A(2);
std::cout << a.get_val() << std::endl;
// pointer way
A* ap;
ap = new A(13);
std::cout << ap->get_val() << std::endl;
delete ap;
ap = new A(232);
std::cout << ap->get_val() << std::endl;
delete ap;
return 0;
}
我最初創建了一個超出默認構造函數的對象,然後將tmp r值對象A(x)
指定爲a
。這最終稱爲assignment operator
。因此,在這種方法也有涉及3個步驟哪一種在指針方式和非指針方式之間進行選擇?
(非指針方式)
1)構造
2)賦值運算符
3)析構函數
凡當我用指針它只需要兩步
(指針方式)
1)構造
2)析構函數
我的問題是我應該用非指針的方式來創建新的類或我應該使用指針方式。因爲我曾經說過我應該避免使用指針(我知道我也可以在這裏使用shared_ptr)。
在「現代」C++(自C++ 11以來)指針很少需要多態之外。 –
你爲什麼這麼說?由於std :: moves?因爲std :: moves避免了賦值操作符? – pokche
你也可以很容易地在單步執行「非指針方式」的初始化,例如, 'A a = 1;'或'A a(1);',從而跳過分配步驟。 –