gpt4 book ai didi

c++ - 设置授予成员常量访问权限的成员函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:20 27 4
gpt4 key购买 nike

我有一个包含一些大对象的类,我需要以 const 方式访问这些对象。为此,我使用 getABC() 成员函数将这些对象复制到外部世界。是否可以直接访问它们,因为在我的情况下复制操作非常慢? shared_ptr 会更好,而且我想避免制作元组只是为了在 getABC() 中返回它们

#include <iostream>
#include <vector>

using namespace std;

class foo {
private:
int a;
vector<int> b; // HUGE OBJECT
vector<int> c; // HUGE OBJECT
public:
foo(int a_, vector<int> b_, vector<int> c_) : a(a_), b(b_), c(c_) { }
void printfoo() {
cout << "a = " << a << endl;
cout << "b = ";
for(auto v:b) {
cout << v << " ";
}
cout << endl;
cout << "c = ";
for(auto v:c) {
cout << v << " ";
}
cout << endl;
}
void getABC(int & a_in, vector<int> & b_in, vector<int> & c_in ) const {
a_in = a;
b_in = b; // SLOW
c_in = c; // SLOW
}

};


int main() {

int in = 4;
vector<int> inA {1, 2, 3, 5};
vector<int> inB {2, 2, 3, 5};

foo bar(in, inA, inB);
bar.printfoo();

// GET THE MEMBERS
int out = 0;
vector<int> outA;
vector<int> outB;
bar.getABC(out, outA, outB);


// PRINT
cout << "OUT = " << out;
cout << "\nOUTA = ";
for(auto const &v : outA ) {
cout << v << " ";
}
cout << endl;
cout << "OUTB = ";
for(auto const &v : outA ) {
cout << v << " ";
}
cout << endl;

return 0;
}

最佳答案

I want to avoid making tuples just to return them in the getABC()

为什么?这似乎是返回对多条数据的引用的最直接方法:

tuple<const int&, const vector<int>&, const vector<int>&> getABC() const
{ return std::make_tuple(std::cref(a), std::cref(b), std::cref(c)); }


auto refs = bar.getABC();
for (auto& x : std::get<1>(refs))
// ...

或者创建一个命名结构来返回:

struct DataRefs {
int a;
const std::vector<int>& b;
const std::vector<int>& c;
};

DataRefs getABC() const { return { a, b, c }; }

这样做的好处是您不需要使用 std::get<N>访问成员,并且可以只使用合理的名称:

auto refs = bar.getABC();
for (auto& x : refs.b)
// ...

根据您的评论,您可能想要这样的东西,但这将是一个愚蠢的界面:

void getABC(const int*& pa, const std::vector<int>*& pb, const std::vector<int>*& pc) const
{
pa = &a;
pb = &b;
pc = &c;
}

你可以这样使用:

int* a;
std::vector<int>* b;
std::vector<int>* c;
bar.getABC(a, b, c);
for (auto& x : *b)
// ...

如您所见,这对调用者来说更加冗长,而且丑陋而不是惯用的 C++。

或者您可以将数据移动到一个单独的子对象中:

class foo
{
struct data
{
int a;
std::vector<int> b;
std::vector<int> c;
};
data m_data;

public:
const data& getData() const { return m_data; };
};

auto& refs = bar.getData();
for (auto& x : refs.b)
// ...

关于c++ - 设置授予成员常量访问权限的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42237787/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com