第一种使用所谓的一个initialization list。
当你输入构造函数的主体时,所有的类成员都必须被构造(所以它们可以被使用)。所以,如果你有这样的:
class Foo
{
public:
Foo()
: str() // this is implicit
{
str = "String.";
}
private:
std::string str;
};
所以,str
被构建,然后分配。最好是:
class Foo
{
public:
Foo()
: str("String.")
{
}
private:
std::string str;
};
因此str
得到直接构建。这对你的情况并没有什么不同,因为指针没有构造函数。
在构造函数中使用初始化列表而不是运行代码通常被认为是很好的做法。 初始化列表应该用于初始化,构造函数应该用于运行代码。
另外,为什么要使用指向字符串的指针?如果你想要一个字符串,使用一个字符串;不是指向字符串的指针。机会是,你实际上想要一个字符串。
更多关于初始化列表:
初始化列表有更多的用途比类的初始化刚刚成员。它们可以被用来传递参数为基础的构造函数:
class Foo
{
public:
Foo(int i) { /* ... */ }
}
class Bar
: public Foo
{
public:
Bar()
: Foo(2) // pass 2 into Foo's constructor.
// There is no other way of doing this.
{
/* ... */
}
};
或常量成员:
class Foo
{
public:
Foo()
: pi(3.1415f)
{
pi = 3.1415f; // will not work, pi is const.
}
private:
const float pi;
};
或参考:
class Foo
{
public:
Foo(int& i)
: intRef(i) // intRef refers to the i passed into this constructor
{
intRef = i; // does *not* set intRef to refer to i!
// rather, it sets i as the value of
// the int intRef refers to.
}
private:
int &intRef;
};
这不完全相同,因为如果你做后者,你不能创建一个常量图像。在这种情况下可能不是你想要做的事情,但对于更轻量级的类型可能有意思。 – 2009-08-06 07:29:22
如果你有一个const图像,你可能也需要一个const m_sFileName,所以我没有看到问题。 – MSalters 2009-08-06 07:53:24