小编c.h*_*hes的帖子

Why do C++ STL container begin and end functions return iterators by value rather than by constant reference?

As I look at the standard for different STL objects and functions, one thing that doesn't make sense to me is why would the begin() and end() functions for container objects return an iterator by value rather than by constant reference? It seems to me that iterators could be held by the container object internally and adjusted whenever the container is mutated. This would mitigate the cost of creating unnecessary temporaries in for loops like this:

for (std::vector<int>::iterator it=my_vec.begin(); it!=my_vec.end(); …
Run Code Online (Sandbox Code Playgroud)

c++ optimization containers stl

3
推荐指数
2
解决办法
1447
查看次数

对象构造后初始化 const 成员变量

我经常发现自己希望对象的成员变量可以是 const,但系统允许在构造后初始化该 const 变量。有没有一种机制可以让我这样做?

为了澄清这一点,这里有一个例子:

class A
{
public:
    A(){}
    initialize(int x) { c = x; }
private:
    const int c;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做这样的事情。我在构造时没有这些信息,所以我不能简单地将初始化移动到构造函数的初始化列表中。

c++ constants

2
推荐指数
1
解决办法
1656
查看次数

标签 统计

c++ ×2

constants ×1

containers ×1

optimization ×1

stl ×1