[英]How to make 'this' into std::unique_ptr?
在下面的代碼中,我如何從下面的Object::get
function 返回相同的 object。 請查看 function 中的注釋。
function 返回具有給定id
的新Object
的std::unique_ptr
。 但是如果id
與對象的id
相同,或者對象的id
設置為error
,則應該返回this
指針(即同一個對象)。 那么如何從Object::get
function 返回相同的 object 呢?
#include <set>
#include <memory>
#include <iostream>
class IObject
{
public:
virtual std::unique_ptr<IObject> get(std::string id) = 0;
virtual void fun() = 0;
virtual ~IObject() {}
};
class Object : virtual public IObject
{
public:
Object(std::string id) : id_(id) {}
virtual std::unique_ptr<IObject> get(std::string i)
{
if((id() == i) || (id() == "error")) {
// Return the same object
//return this; // How to achieve this? How to return the same object?
return std::make_unique<Object>(id()); // This does not return the same object.
}
if(ids.end() == ids.find(i)) {
return std::make_unique<Object>("error");
}
return std::make_unique<Object>(i);
}
virtual void fun()
{
std::cout << "Object is: " << id() << std::endl;
}
std::string const& id() const
{
return id_;
}
private:
static std::set<std::string> const ids;
std::string id_;
};
std::set<std::string> const Object::ids{"id0", "id1", "id2", "id3"};
int main()
{
auto o = std::make_unique<Object>("id0");
o->get("id1")->get("id2")->get("id3")->fun();
o->get("id1")->get("idN")->get("id2")->fun();
o->get("id1")->get("idN")->get("id2")->get("id3")->fun();
o->get("id1")->get("id2")->get("id2")->fun();
o->get("id1")->get("id2")->get("id2")->get("id3")->fun();
return 0;
}
unique_ptr
代表 object 的唯一所有權。 該類型的設計使得只有一個unique_ptr
管理此 object 的生命周期; 這就是為什么它被稱為“獨特”。
因此,如果某人已經this
object 擁有唯一所有權,則您不能將其唯一所有權授予其他人。 因為那樣它就不是唯一的所有權。 您甚至不能賦予當前所有者this
的唯一所有權,因為那樣他們將在兩個地方擁有它。
你想要的不是一件合理的事情。 您要么打算擁有共享所有權語義(因此應該使用shared_ptr
或具有enable_shared_from_this
的等價物),要么您不希望 function 返回unique_ptr
。
你的問題的答案很簡單。
return std::unique_ptr<Object>(this);
然而,正如尼科爾在他的回答中指出的那樣,這幾乎肯定不是你想要的。
考慮以下代碼:
Object foo("foo");
foo.get();
繁榮! 您剛剛在未在堆上分配的一些 memory 上調用了free
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.