Hey, guys, I have a few questions regarding direct initialization and copy initialization.
1. if I defined a variable and then defined another variable using the first variable, is this direct initialization or copy initialization?
1 2
|
string a(10,'a');
string b(a);
|
so in the case above, b is initialized with the constructor of string class or the copy constructor of string class?
2. I read on my textbook that copy initialization would happen when we return an object from a function that has a nonreference return type. I'm wondering what exactly is the underlying mechanism behind this? cuz in order to verify this claim, I tried it with an user-defined class which is shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Hasptr
{
public:
Hasptr(const string &s = string()): ps(new string(s)), i(0) {cout << 0 << endl;}
Hasptr(const Hasptr& ori){*ps = *ori.ps; i = ori.i; cout << 1 << endl;}
void print(){cout << *ps << " " << i << endl;}
private:
string *ps = new string();
int i;
};
Hasptr func(Hasptr &a) { Hasptr b = a; return b;}
int main()
{
Hasptr x("fs");
Hasptr y = func(x);
}
|
Basically, there is a class named Hasptr with a constructor which would print '0' every time it's called and another copy constructor which would print '1' every time being called, so in the main function, I defined an object named x with type Hasptr, and called a function named func to initialize another object y with type Hasptr.
and the output of this program is
while I actually expect the output to be
The 0 is because I first directly initialized the object x. The first 1 is because I called the function func to initialize y and func used copy initialization once in its function body. The second 1 is because I returned a object b from function func and this function had nonreference return type, so according to my textbook, a copy initialization should happen here once. And the last 1 is because the object y is also copy initialized.
These 2 questions are all I can think of for now. I hope that you guys can help me out here. I'd really appreciate it!