码迷,mamicode.com
首页 > 编程语言 > 详细

c++细节

时间:2020-05-14 19:01:59      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:int   hash   find   cell   span   而不是   size   let   nts   

1,指针:

未初始化的指针通常会使得程序崩溃;

在C ++中,有几种使用其零参数构造函数创建对象的方法。

m = new IntCell( ); // OK

m = new IntCell{ }; // C++11

m = new IntCell; // Preferred in this text 

通常使用最后一种;

为避免内存泄漏,通常在局部变量使用完之后删除;

地址运算符&;

int main(void)
{
    IntCell *m;
    
    m=new IntCell{0};
    m->write(5);
    cout<<"Cell contents: "<<m->read()<<endl;

    delete m;
    system("pause");
    return 0;
}

IntCell具体定义 见上章

2,引用:

在C ++ 11中,我们可以有两种类型的引用:左值引用和右值引用。

右值引用作用并不明显,

string str = "hell";

string & rstr = str; // rstr is another name for str

rstr += ’o’; // changes str to "hello"

bool cond = (&str == &rstr); // true; str and rstr are same object

string & bad1 = "hello"; // illegal: "hello" is not a modifiable lvalue

string & bad2 = str + ""; // illegal: str+"" is not an lvalue

string & sub = str.substr( 0, 4 ); // illegal: str.substr( 0, 4 ) is not an lvalue 

 

string str = "hell";

string && bad1 = "hello"; // Legal

string && bad2 = str + ""; // Legal

string && sub = str.substr( 0, 4 ); // Legal 

类型后边 && 表示右值引用,一个&表左值引用;

 

左值引用的使用:

#1:给复杂名字重命名

学散列时用:

auto & whichList = theLists[ myhash( x, theLists.size( ) ) ];

if( find( begin( whichList ), end( whichList ), x ) !=end( whichList ) )

  return false;

whichList.push_back( x );

用whichlist替代一长串,接下来就不用被写入四次

  auto whichList = theLists[ myhash( x, theLists.size( ) ) ];

不会有上边那种效果,它只会copy一下theLists[ myhash( x, theLists.size( ) ) ]里的内容,然后push_back只会改变现有的,而不是原来的;

#2:循环范围的使用

给vector中的每个值+1,

for( int i = 0; i < arr.size( ); ++i )

  ++arr[ i ];

原始写法:x是假定向量中每个值的copy

for( auto x : arr )// broken

  ++x;

我们真正想要的是x是向量中每个值的另一个名称,如果x是引用,这很容易做到:
for(auto&x:arr)//适用于

  ++ x;

#3:避免复制

找vector中最大值:

auto x = findMax( arr );

很多情况下,只需要值而不做改变,那么引用显然会比直接复制好,

auto & x = findMax( arr );

3,参数传递:

...

 

c++细节

标签:int   hash   find   cell   span   而不是   size   let   nts   

原文地址:https://www.cnblogs.com/sweetlittlebaby/p/12890454.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!