2009年2月25日星期三

模板是什么

无论是类还是类模板都不能有virtual member function template.

模板类特化或者部分特化之后,就是一个独立的类.

模板参数要求的是类型,而不是变量.

2009年2月4日星期三

explicit initialization的新知

对于水母精华区里多次讲到的T t = v;的实际过程,这里(叫做explicit initialization)有很明确的解释:
其中一个之前没有注意到的问题是,尽管编译器可以将2步优化为1步,但要求copy ctor必须为public的,否则就会失败。
Even if, as in the above example, the compiler does not generate a call to the copy constructor, it must be available. This is illustrated in the following program (available as test-2.C) which does not compile. 
#include    
    class T {
        public:
        T(int i): data_(i) { std::cerr << "T::T(int)" <<>
        private:
        T(const T&) { std::cerr << "T::T(const T&)" <<>
         int data_;
     };
    int main(int, char**) {
        T t1(3); // OK
        T t2 = 3; // Error: T::T(const T&) private.
     }
For the above program, the compiler issues the following error message
test-2.C: In function `int main(int, char**)':  
test-2.C:6: `T::T(const T&)' is private  
test-2.C:13: within this context  
test-2.C:13: initializing temporary from result of `T::T(int)'

explicit

explicit 只对有一个参数(或者有多个参数,但除了第一个,其他参数都有默认值)的构造函数起作用。explicit针对的是其他类型在向某class转换时必须遵循构造函数的参数类型,而构造函数的参数类型则可以进行implicit转换。两者对应的层次不同。
google的style guide里写道:
 We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name);

The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments. 
cppreference的例子很好:

      struct foo {

      explicit foo( int a )

        : a_( a )

      { }

 

      int a_;

    };

 

    int bar( const foo & f ) {

      return f.a_;

    }

 

    bar( 1 );  // fails because an implicit conversion from int to foo

               // is forbidden by explicit.

 

    bar( foo( 1 ) );  // works -- explicit call to explicit constructor.

 

    bar( static_cast( 1 ) );  // works -- call to explicit constructor via explicit cast.

 

    bar( foo( 1.0 ) );  // works -- explicit call to explicit constructor

                        // with automatic conversion from float to int.

2009年2月2日星期一

Effective STL学习

如果STL的容器元素为指针,需要在析构时析构所有元素,而自己编写遍历析构每个元素的代码可能会由于中间出现的exception导致内存泄露。所以,推荐的做法是使用boost::shared_ptr作为容器的元素。
永不建立auto_ptr的容器,也可以说auto_ptr同STL结合并不良好。

值传递或返回时,需要确保两件事:对象应该小;必须单态。