copy constructor problem

C

ciccio

Hi,

I have a problem and I don't know what is going on here.

I basically call a function defined as test(const bar &a), in which I
define a const reference to an object foo which comes from bar. At this
point I have a copy constructor which should not be the case.

A working example you can find below which explains it a bit better.

Am I just doing something stupidly wrong here?

Thanks for the help in any case.

// EXAMPLE HERE

#include <iostream>

class foo {
public:
foo() { std::cout << "i foo" << std::endl; }
foo(const foo &c) { std::cout << "c foo" << std::endl; }
~foo() { std::cout << "d foo" << std::endl; }
};

class bar {
public:
bar(void);
~bar(void);

foo operator()(void) const { return f; };
private:
foo f;
};

bar::bar(void) { }
bar::~bar(void) { }

void test(const bar &b) {
std::cout << "start test" << std::endl;
const foo &f2 = b();
std::cout << "end test" << std::endl;
}

int main(void) {
bar b;
test(b);
}

// THE OUTPUT

i foo
start test
c foo << DONT EXPECT THIS
end test
d foo
d foo
 
C

Christopher

Hi,

I have a problem and I don't know what is going on here.

I basically call a function defined as test(const bar &a), in which I
define a const reference to an object foo which comes from bar. At this
point I have a copy constructor which should not be the case.

A working example you can find below which explains it a bit better.

Am I just doing something stupidly wrong here?


You aren't understanding that your bar::eek:perator() is returning by
value, which creates a temporary object when it returns.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,690
Latest member
MacGyver

Latest Threads

Top