EffectiveC++ 条款04:确定对象被使用前已先被初始化

#include <iostream>
#include <string>

class Value
{
private:
	std::string value;

public:
	Value() { 
		std::cout << "default construct" << std::endl;
	}
	
	Value(std::string str) :value(str) {
		std::cout << "construct: value is " <<  str << std::endl;
	 }
};

class Test
{
private:
	Value m_v;
public:
	Test(Value v)
	{
		m_v = v;
	}
};
int main(int argc, char **argv)
{
	Test  t(Value("hello world"));
	return 0;
}

 输出:

#include <iostream>
#include <string>

class Value
{
private:
	std::string value;

public:
	Value() { 
		std::cout << "default construct" << std::endl;
	}
	
	Value(std::string str) :value(str) {
		std::cout << "construct: value is " <<  str << std::endl;
	 }
};

class Test
{
private:
	Value m_v;
public:
	Test(Value v):m_v(v)
	{
	}
};
int main(int argc, char **argv)
{
	Test  t(Value("hello world"));
	return 0;
}

输出:

不需要调用默认构造函数

猜你喜欢

转载自blog.csdn.net/LIJIWEI0611/article/details/108563722