【发布时间】:2020-10-07 17:13:48
【问题描述】:
我目前正在阅读 C++ Primer 5th edition,这是本书中的代码示例之一。我对这行代码auto ret = StrBlobPtr(*this, data->size()); 感到困惑,如果我理解正确,这行代码会创建一个临时 StrBlobPtr 对象并调用此构造函数StrBlobPtr(StrBlob& a, size_t sz = 0) : wptr(a.data), curr(sz) {} 但我不明白auto ret= 是如何从临时对象中获取返回值的,所以我的问题是
-
ret如何获取StrBlobPtr创建的对象? -
end如何返回一个StrBlobPtr,它保存了StrBlob类中std::shared_ptr<vector<string>> data;中的最后一个值。
我说的那段代码一直在底部。
#pragma once
#include <vector>
#include <string>
#include <initializer_list>
#include<stdexcept>
#include <memory>
#include <exception>
using std::vector;
using std::string;
class StrBlobPtr;
class StrBlob {
public:
using size_type = vector<string>::size_type;
friend class StrBlobPtr;
StrBlobPtr begin();
StrBlobPtr end();
StrBlob() : data(std::make_shared<vector<string>>()) {}
StrBlob(std::initializer_list<string> il)
: data(std::make_shared<vector<string>>(il))
{
}
size_type size() const { return data->size(); }
bool empty() const { return data->empty(); }
void push_back(const string& t) { data->push_back(t); }
void pop_back()
{
check(0, "pop_back on empty StrBlob");
data->pop_back();
}
std::string& front()
{
check(0, "front on empty StrBlob");
return data->front();
}
std::string& back()
{
check(0, "back on empty StrBlob");
return data->back();
}
const std::string& front() const
{
check(0, "front on empty StrBlob");
return data->front();
}
const std::string& back() const
{
check(0, "back on empty StrBlob");
return data->back();
}
private:
void check(size_type i, const string& msg) const
{
if (i >= data->size()) throw std::out_of_range(msg);
}
private:
std::shared_ptr<vector<string>> data;
};
class StrBlobPtr {
public:
StrBlobPtr() : curr(0) {}
StrBlobPtr(StrBlob& a, size_t sz = 0) : wptr(a.data), curr(sz) {}
bool operator!=(const StrBlobPtr& p) { return p.curr != curr; }
string& deref() const
{
auto p = check(curr, "dereference past end");
return (*p)[curr];
}
StrBlobPtr& incr()
{
check(curr, "increment past end of StrBlobPtr");
++curr;
return *this;
}
private:
std::shared_ptr<vector<string>> check(size_t i, const string& msg) const
{
auto ret = wptr.lock();
if (!ret) throw std::runtime_error("unbound StrBlobPtr");
if (i >= ret->size()) throw std::out_of_range(msg);
return ret;
}
std::weak_ptr<vector<string>> wptr;
size_t curr;
};
StrBlobPtr StrBlob::begin() { return StrBlobPtr(*this); }
StrBlobPtr StrBlob::end()
{
auto ret = StrBlobPtr(*this, data->size());
return ret;
}
【问题讨论】:
-
C++ 中的初始化是...complicated。在这种情况下,您会得到Copy Initialization。
-
auto x = T();与T x();相同(除了不解释为函数声明)
标签: c++ c++11 constructor