我正在研究某人编写的这段简洁的代码。
// C++:智能指针以及如何编写自己的智能指针
// https://medium.com/swlh/c-smart-pointers-and-how-to-write-your-own-c0adcbdce04f
我创建这个类是为了测试它:
class Box
{
private:
struct{
int length, width, height;
} properties;
public:
//Box() = delete;
Box(){
this->properties = {0, 0, 0}; // fix undefined reference
};
Box(const int &l, const int &w, const int &h){
this->properties = {l, w, h};
}
// inline void operator= (const int &l) {
// this->properties = {l};
// }
// Box& operator*()
// {
// return (Box&&)(this->properties);
// }
int get_length(){return this->properties.length;};
int get_width(){return this->properties.width;};
int get_heigth(){return this->properties.height;};
void set_length(int var){this->properties.length =var;};
void set_width(int var){this->properties.width = var;};
void set_heigth(int var){this->properties.height = var;};
};
你不能这样做:
unique_ptr<Box[]> *boxArr = new Box[5];
unique_ptr<Box> *boxArr3(new Box);
unique_ptr<Box[]> *boxArr2(new Box[5]);
错误:
Cannot initialize a variable of type 'unique_ptr<Box[]> *' with an rvalue of type 'Box *'
第二:如何强制该对象只能创建为指针对象。
那是什么样的对象属性或运算符重载?
这就是您在使用“智能”指针时想要的属性。
关于如何设置类的构造函数等属性、将它们设置为默认值、删除或更确切地说监督可能的属性,还有更多可能。
这可能是您想要做的:
std::unique_ptr<Box[]> boxArray{new Box[5]};
std::unique_ptr<Box> box{new Box};
您可以与工厂操作员一起完成:
struct Foo
{
static Foo * instance()
{
return new Foo();
}
private:
Foo() = default;
};
int main()
{
Foo * f = Foo::instance();
delete f;
return 0;
}
创建构造函数
private
可以防止直接实例化/继承。