小编arv*_*ind的帖子

如何为c ++程序分配内存

考虑以下计划:

#include <string>
#include <iostream>

class B {
  private:
    std::string s;

  public:
    B() { s = fun(); }
    std::string fun() { return "hello"; }
    void print() {
        std::cout << s;
    }
};

int main(){
    B b;
    b.print();
}
Run Code Online (Sandbox Code Playgroud)

输出是 Hello

我的问题是:

  1. 在哪个序列中为数据成员分配内存(在本例中为's').
  2. 在构造函数中调用fun()时是否存在Object.

我怀疑的是我如何在b对象上调用一个尚未由构造函数创建的函数.

c++

3
推荐指数
1
解决办法
135
查看次数

为什么lambda采用变量的初始值

问题是为什么程序打印id:0,id:1,id:2,42而不是id:42,id:43,id:44,45.

int main()
{

    int id = 0;
    auto f = [id] () mutable {
        std::cout << "id: " << id << std::endl;
        ++id; // OK
    };

    id = 42;
    f();
    f();
    f();
    std::cout << id << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ lambda stl

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

将子类对象作为异常抛出

在读取异常时,我知道在抛出对象时,总是基于静态类型信息构造对象。如果发生异常,我们如何抛出子类对象?以下是《更有效的C ++》一书中的几行内容:

class Widget{...};

class SpecialWidget: public Widget {...};

void passAndThrowWidget()
{
    SpecialWidget localSpecialWidget;
    ...
    Widget& rw = localSpecialWidget;
    throw rw; // this throws an exception of type widget!
}
Run Code Online (Sandbox Code Playgroud)

即使rw指向,也会在此处引发Widget异常SpecialWidget。那是因为rw的静态类型是Widget,而不是Special-Widget。rw实际上是指S pecialWidget,您的编译器并不关心。他们只关心rw的静态类型。

这就解释了为什么会发生这种情况,但没有提供解决问题的方法。

c++ c++11

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

标签 统计

c++ ×3

c++11 ×1

lambda ×1

stl ×1