相关疑难解决方法(0)

关于向量增长

曾经阅读过Book:C++ Primer,Third Edition作者:Stanley B. Lippman,JoséeLajoie

到目前为止发现1个错误....在根据第6.3条给出的程序中,一个向量如何生长,这个程序在couts中错过了一个"<"!给出的计划是:

#include <vector>
#include <iostream>

int main(){
vector< int > ivec;
cout < "ivec: size: " < ivec.size()
< " capacity: "  < ivec.capacity() < endl;

for ( int ix = 0; ix < 24; ++ix ) {
ivec.push_back( ix );
cout < "ivec: size: " < ivec.size()
< " capacity: "  < ivec.capacity() < endl;
}    
}
Run Code Online (Sandbox Code Playgroud)

现在我纠正了这个问题.本书后面的内容如下:"在Rogue Wave实现中,ivec定义后的大小和容量均为0.然而,在插入第一个元素时,ivec的容量为256,其大小为1."

但是,在纠正和运行代码时,我得到以下输出:


ivec: size: 0 capacity: 0
ivec[0]=0 ivec: size: 1 capacity: 1
ivec[1]=1 ivec: size: …
Run Code Online (Sandbox Code Playgroud)

c++ visual-c++

22
推荐指数
2
解决办法
2万
查看次数

如果构造函数抛出异常会发生什么?

那我们会得到UB吗?我试过这个:

#include <iostream>

struct B
{
    B(){ std::cout << "B()" << std::endl; }
    ~B(){ std::cout << "~B()" << std::endl; }
};

struct A
{
    B b;
    A(){ std::cout << "A()" << std::endl; throw std::exception(); }
    ~A(){ std::cout << "~A()" << std::endl; }
};

int main()
{
    A a;
}
Run Code Online (Sandbox Code Playgroud)

desctructor没有被要求netither A也没有B.实际输出:

B()
A()
terminate called after throwing an instance of 'std::exception'
  what():  std::exception
bash: line 7: 21835 Aborted                 (core dumped) ./a.out
Run Code Online (Sandbox Code Playgroud)

http://coliru.stacked-crooked.com/a/9658b14c73253700

因此,在块范围变量初始化期间构造函数抛出的任何时候,我们都得到UB吗?

c++ initialization

22
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×2

initialization ×1

visual-c++ ×1