“const”的使用有多少和哪些是。在C ++? [英] How many and which are the uses of "const" in C++?

查看:114
本文介绍了“const”的使用有多少和哪些是。在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个新手C ++程序员,有一些看起来还是很模糊的结构,其中之一是 const 。你可以在这么多地方使用它,有这么多不同的效果,几乎不可能为初学者出来活着。一些C ++的大师永远解释各种用法和是否和/或为什么不使用它们?

解决方案

使用:



绑定一些临时的引用到const,以延长其生命周期。引用可以是一个基础和析构函数它不需要是虚拟的 - 正确的析构函数仍然被调用:

  ScopeGuard const& guard = MakeGuard(& cleanUpFunction); 



说明,使用代码:

  struct ScopeGuard {
〜ScopeGuard(){} // not virtual
};

template< typename T> struct Derived:ScopeGuard {
T t;
Derived(T t):t(t){}
〜Derived(){
t // call function
}
};

template< typename T>派生的< T> MakeGuard(T t){return Derived T(t); }

这个技巧用于Alexandrescu的ScopeGuard实用程序类。一旦临时超出范围,Derived的析构函数被正确调用。上面的代码错过了一些小细节,但这是很大的问题。






使用const告诉别人方法不会改变逻辑状态

  struct SmartPtr {
int getCopies()const {return mCopiesMade; }
};




使用写入时写入类别的const ,让编译器帮助您决定何时和何时不需要复制。  struct MyString {
char * getData(){/ * copy:caller may write * / return mData; }
char const * getData()const {return mData; }
};

说明:您可能希望在长时间复制时共享数据因为原始数据和复制对象的数据保持不变。一旦一个对象改变了数据,你现在需要两个版本:一个对于原始,一个对于副本。也就是说,您可以 复制到任一对象,这样他们现在都有自己的版本。



使用代码

  int main(){
string const a =1234;
string const b = a;
//为COW字符串输出相同的地址
cout<< (void *)& a [0]< ,< (void *)& b [0];上面的代码片段在我的GCC上打印了相同的地址,因为使用的C ++库(例如:


$ b <实现写时复制 std :: string 。两个字符串,即使它们是不同的对象,它们的字符串数据共享相同的内存。使 b 非const将更喜欢运算符[] 的非const版本,而GCC将创建一个因为我们可以更改它,它不能影响 a !的数据。

  int main(){
string const a =1234;
string b = a;
//输出不同的地址!
cout<< (void *)& a [0]< ,< (void *)& b [0];
}




要让复制构造函数从const对象和临时表进行复制

  struct MyClass {
MyClass(MyClass const& that){/ * make copy of the * /}
};




  double const PI = 3.1415; 




 > 

void PrintIt(Object const& obj){
// ...
}


As a novice C++ programmer there are some constructs that look still very obscure to me, one of these is const. You can use it in so many places and with so many different effects that is nearly impossible for a beginner to come out alive. Will some C++ guru explain once forever the various uses and whether and/or why not to use them?

解决方案

Trying to collect some uses:

Binding some temporary to reference-to-const, to lengthen its lifetime. The reference can be a base - and the destructor of it doesn't need to be virtual - the right destructor is still called:

ScopeGuard const& guard = MakeGuard(&cleanUpFunction);

Explanation, using code:

struct ScopeGuard { 
    ~ScopeGuard() { } // not virtual
};

template<typename T> struct Derived : ScopeGuard { 
    T t; 
    Derived(T t):t(t) { }
    ~Derived() {
        t(); // call function
    }
};

template<typename T> Derived<T> MakeGuard(T t) { return Derived<T>(t); }

This trick is used in Alexandrescu's ScopeGuard utility class. Once the temporary goes out of scope, the destructor of Derived is called correctly. The above code misses some small details, but that's the big deal with it.


Use const to tell others methods won't change the logical state of this object.

struct SmartPtr {
    int getCopies() const { return mCopiesMade; }
};


Use const for copy-on-write classes, to make the compiler help you to decide when and when not you need to copy.

struct MyString {
    char * getData() { /* copy: caller might write */ return mData; }
    char const* getData() const { return mData; }
};

Explanation: You might want to share data when you copy something as long as the data of the originally and the copie'd object remain the same. Once one of the object changes data, you however need now two versions: One for the original, and one for the copy. That is, you copy on a write to either object, so that they now both have their own version.

Using code:

int main() {
    string const a = "1234";
    string const b = a;
    // outputs the same address for COW strings
    cout << (void*)&a[0] << ", " << (void*)&b[0];
}

The above snippet prints the same address on my GCC, because the used C++ library implements a copy-on-write std::string. Both strings, even though they are distinct objects, share the same memory for their string data. Making b non-const will prefer the non-const version of the operator[] and GCC will create a copy of the backing memory buffer, because we could change it and it must not affect the data of a!

int main() {
    string const a = "1234";
    string b = a;
    // outputs different addresses!
    cout << (void*)&a[0] << ", " << (void*)&b[0];
}


For the copy-constructor to make copies from const objects and temporaries:

struct MyClass {
    MyClass(MyClass const& that) { /* make copy of that */ }
};


For making constants that trivially can't change

double const PI = 3.1415;


For passing arbitrary objects by reference instead of by value - to prevent possibly expensive or impossible by-value passing

void PrintIt(Object const& obj) {
    // ...
}

这篇关于“const”的使用有多少和哪些是。在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆